December 2018
Beginner to intermediate
796 pages
19h 54m
English
From within a class method, we can refer to an instance by means of a special argument, called self by convention. self is always the first attribute of an instance method. Let's examine this behavior together with how we can share, not just attributes, but methods with all instances:
# oop/class.self.pyclass Square: side = 8 def area(self): # self is a reference to an instance return self.side ** 2sq = Square()print(sq.area()) # 64 (side is found on the class)print(Square.area(sq)) # 64 (equivalent to sq.area())sq.side = 10print(sq.area()) # 100 (side is found on the instance)
Note how the area method is used by sq. The two calls, Square.area(sq) and sq.area(), are equivalent, and teach us ...
Read now
Unlock full access