Search⌘ K

Constructors and self

Explore how constructors in Python classes initialize instance variables using the __init__ method and understand the vital role of self as the first parameter in class methods. Learn the distinctions of Python's object model compared to other languages and how to properly manage object attributes.

Python classes vs other languages

If you are familiar with classes and objects in an other language, classes and objects are very similar in Python, except for the annoying word self, which seems to be required everywhere.

Constructors in Python classes

Remember that each object we create from a class has its own copy of each of the fields (instance variables) of that class. If we have two Person objects named joe and jane, each of them will have a name field and an age field.

Briefly, the name self used inside a class definition is the particular object we are talking to.

Every method within a class must have self as its first parameter.

If you remember the Person class example in the previous lesson, it had a limitation that every instance created from it will be exactly the same. We can overcome this using ...