Using super()

Once in a while, you need to access parent class methods and attributes from within the instance—for example, when you initiate a new one and need to execute the parent class's initialization logic. For that, we can use a built-in function called super. It is very easy to use—just call it from within a class—and it will return a proxy object of a direct parent with access to all its methods and attributes. Take a look at the following snippet:

class Shark(Fish):

def __init__(self, w=5000, teeth=121):
self.teeth = teeth
super().__init__(w=w)

Here, we create a new class called Shark, inheriting from Fish. This new class has its own custom initialization code, but it also utilizes the __init__ method of the Fish class via the super method. By doing so, this new class is storing the weight of the fish without writing the same code again:

>>> S = Shark()
>>> S.weight
50000
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.73.147