InitReturnsObject
An __init__
method needs to return an object, and the object requires to be the same type as the surrounding class.
__init__ needs to return an object
__init__ cannot return values other than None
CorrectionHere is what's right.
The __init__
method cannot return values other than None
. This method is called immediately after the object is instantiated, and should contain code to initialize the attributes of the created object (the object referred to by self
).
OriginWhere could this misconception come from?
This misconception may come from how newly created objects are used:
class Animal:
def __init__(self, name):
self.name = name
cat = Animal('tom')
In the above code, the expression Animal('tom')
produces a value. Students may believe that for it to produce a value, the __init__
method has to produce that value. They may believe that Animal(...)
is an expression that only results in a call to __init__
.
Instead, the object is not created by the __init__
method, but by the evaluation of the Animal('tom')
expression, which instantiates the object and then calls the __init__
method to initialize its attributes.
SymptomsHow do you know your students might have this misconception?
Students might do the following:
- write an
__init__
method that returnsself
- write an
__init__
method, e.g. of a classAnimal
, that returnsAnimal()