The __init__ constructor and self
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
Usually each object has its own data: one cat is called Murka, another Barsik. They are set in a special method __init__ — the constructor. It is called automatically when an object is created:
class Cat:
def __init__(self, name, age):
self.name = name # an attribute of the object
self.age = age
def describe(self):
return f"{self.name}, {self.age} y.o."
murka = Cat("Murka", 3)
murka.name # 'Murka'
murka.describe() # 'Murka, 3 y.o.'
What self is. It's the very object the method is working with right now. When you write murka.describe(), Python actually calls Cat.describe(murka) — self is murka. So:
selfis always the first parameter of a method;- an object's attributes are created and read through
self.<attribute>(for example,self.name); - without
self., a variable inside a method is an ordinary local one and disappears after the call.
The word self is a convention, not a keyword. But everyone writes it, and you should too.
Task. Create a class Rectangle: the constructor takes a width and a height, the method area() returns the area, and the method perimeter() returns the perimeter.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.