1. LPU MCA Semester 1
  2. CAB106
  3. Unit 2

CAB106 · Unit 2: Classes and objects

Class definition, object creation and the init constructor

12 practice questions

Key points

  • A class is a blueprint and an object is an instance
  • __init__ initialises the object and must return None
  • self is passed automatically as the first argument
  • Without __eq__, == compares identity

A class is a blueprint defined with class Name:; an object (instance) is created by calling the class, as in d = Dog("Rex"). The special method __init__(self, ...) initialises the new object; it must return None. The first parameter, self, is the object itself and is passed automatically. Constructors may have default values and keyword arguments, and a missing required argument raises TypeError.

Special methodPurpose
__new__(cls)Creates the instance, runs first
__init__(self)Initialises the instance
__str__(self)Text returned by print and str
__eq__(self, other)Defines ==

Attributes can be added to an object at any time (a.x = 5), and hasattr tests for them. Without __eq__, == compares identity, so two objects with equal data are not equal. A class is itself an object of type type, and isinstance(a, A) tests membership.

Exam trap: forgetting self in a method definition. def hello(): fails with TypeError when called on an instance, because Python passes the instance as an extra argument.

Try two questions

Question 1 · Tier 1, Recall

By convention, what does the first parameter self of an instance method refer to?

  1. The class that defines the method
  2. The parent class of the current class
  3. The module in which the class is written
  4. The object on which the method is being called
Show the answer

D. Python passes the calling object as the first argument, and it is named self by convention.

Why not A: The class itself is passed to a class method as cls.

Why not B: The parent class is reached with super(), not self.

Why not C: A module is not passed to methods automatically.

Question 2 · Tier 1, Recall

Which special method is normally used to initialise the attributes of a newly created object?

  1. __str__
  2. __init__
  3. __del__
  4. __call__
Show the answer

B. __init__ runs right after the object is created and sets its starting attributes.

Why not A: __str__ builds the text shown when an object is printed.

Why not C: __del__ runs when an object is about to be destroyed.

Why not D: __call__ lets an object be called like a function.