Constructor
Let us first look at the __init__()
method. The double underscores on both sides is a Python convention that indicates that this is a magic method that does special things. They are called magic or dunder methods (dunder == double underscores). We will see more of these later.
1
2
3
4
5
6
7
class Person:
def __init__(self, firstname, lastname, age):
self.firstname = firstname
self.lastname = lastname
self.age = age
person = Person("Josiah", "Wang", 20) # invoking the constructor
__init__()
acts as the constructor. When you create a class instance (Line 7), Python will create a new object in a memory heap, and execute the __init__()
method.
The parameter self
is similar to the this
keyword in Java. In Python, when you create a new instance with Person()
in Line 7, what really happens in the background is that a new object is created and assigned to self
. To make it more concrete, below is (most likely) what goes on in the background. Please DO NOT write such code – this is just for illustrative purposes!!
# new object of type Person created in heap, and assigned to the variable self
self = object.__new__(Person)
# The __init__() method for class Person is invoked
Person.__init__(self, "Josiah", "Wang", 20)
return self
So self
is a reference to the new Person
instance that Python has just allocated in heap memory.