Lesson 8
Making Objects the Main Star!
Chapter 3: Classes and attributes
Class constructors
Now, let’s try to print out a message when the Person
object is being created. You will need to define a special __init__()
method inside the class to do this.
1 2 3 4 5 6 |
|
When you run the program, it should output I created a person! It's alive!
, and then <__main__.Person object at 0x7fe70c878c10>
.
In object-oriented programming terms, the __init__()
method is a class constructor. In this method, you can customise what happens after the object has been created.
self
(in Line 2) refers to the Person
object that has just been created. The first parameter of __init__()
should always be self
. This is so that you can manipulate this self
object inside the method. You can technically name it anything, but PEP 8 says that you should use self
for consistency, so always do that!
What actually happens in the background when you say Person()
is that Python will first call Person.__new__()
(another magic method that you can but should not mess with), which will allocate some space in memory for the new (empty) object.
Python then calls Person.__init__(self)
. You can do anything here, but you would typically add attributes to the object (we will do this in the next page; this is actually what self
is partly for!)
Finally, Python will return this new object that has been created to the caller.
There is already a default implementation for the __init__()
method, which is why the code from the previous page worked even without having to define it. Most of the time though, you will want to write your own __init__()
method. Let’s do that properly in the next page!