I understand why super() is used when a class is a subclass of a superclass, but what is the superclass of a class that doesn't specify the superclass in the subclass parameters? Here's my code:
import random
class Sneaky:
sneaky = True
def __init__(self, sneaky=True, *args, **kwargs):
super().__init__(*args, **kwargs)
self.sneaky = sneaky
def hide(self, light_level):
return self.sneaky and light_level < 10
class Agile:
agile = True
def __init__(self, agile=True, *args, **kwargs):
super().__init__(*args, **kwargs)
self.agile = agile
def evade(self):
return self.agile and random.randint(0, 1)
The super() function is used to give access to methods and properties of a parent or sibling class. The super() function returns an object that represents the parent class.
Understanding Python super() with __init__() methods It is known as a constructor in Object-Oriented terminology. This method when called, allows the class to initialize the attributes of the class. The super() function allows us to avoid using the base class name explicitly.
The super() function in Python makes class inheritance more manageable and extensible. The function returns a temporary object that allows reference to a parent class by the keyword super. The super() function has two major use cases: To avoid the usage of the super (parent) class explicitly.
In general it is necessary. And it's often necessary for it to be the first call in your init. It first calls the init function of the parent class ( dict ).
Suppose Sneaky
is used as part of a multiple inheritance class structure such as:
class Sneaky:
sneaky = True
def __init__(self, sneaky=True, *args, **kwargs):
super().__init__(*args, **kwargs)
self.sneaky = sneaky
def hide(self, light_level):
return self.sneaky and light_level < 10
class Person:
def __init__(self, human=True, *args, **kwargs):
super().__init__(*args, **kwargs)
self.human = human
class Thief(Sneaky, Person):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
t = Thief()
print(t.human)
# True
Since
In [62]: Thief.mro()
Out[62]: [__main__.Thief, __main__.Sneaky, __main__.Person, object]
Thief.__init__
's super().__init__(*args, **kwargs)
calls Sneaky.__init__
.Sneaky.__init__
's super().__init__(*args, **kwargs)
calls Person.__init__
. If the super().__init__
call were removed from Sneaky.__init__
, then t.human
would raise
AttributeError: 'Thief' object has no attribute 'human'
because Person.__init__
would not get called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With