Constructors and self

In this lesson, you'll learn about the concept of constructors and the self variable in Python classes.

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 the self parameter.

The following is the same Person class example this time. However, this time it also includes using the self parameter.

Get hands-on with 1400+ tech skills courses.