Reputation: 91
I was doing an exercise that involved multiple inheritances with initializers that had multiple amount of arguments required and thought, how could super() solve this instead of manually call each superclass?
class One:
def __init__(self, address, phone):
self.address = address
self.phone = phone
class Two:
def __init__(self, city):
self.city = city
class Three(One,Two):
def __init__(self, country, address, phone, city):
self.country = country
One.__init__(self, address, phone)
Two.__init__(self, city)
print(f"{address}, " + f"{phone}, " + f"{self.city}, " + f"{self.country}")
i = Three("Acountry", "AnAddress", "Aphone", "Acity")
This works fine, all the arguments are printed well and in order, but i don't know how to implement super()
here.
I tried adding 2 supers on the subclass:
super().__init__(address, phone)
super().__init__(city)
And even add a super() on the parent class to make it point to class Two
:
class One:
def __init__(self, address, phone, city):
self.address = address
self.phone = phone
super().__init__(city)
class Two:
def __init__(self, city):
self.city = city
class Three(One,Two):
def __init__(self, country, address, phone, city):
self.country = country
super().__init__(address, phone)
print(f"{address}, " + f"{phone}, " + f"{self.city}, " + f"{self.country}")
i = Three("Acountry", "AnAddress", "Aphone", "Acity")
It doesn't work.
How can i implement super()
in the original code that works?
Upvotes: 1
Views: 63
Reputation: 61042
You should read this article by Raymond Hettinger, which goes over how super
is designed to work, and outlines how your classes using it should look. He recommends passing arguments as keyword arguments and calling super().__init__
at the end of every __init__
:
class One:
def __init__(self, address, phone, **kwargs):
self.address = address
self.phone = phone
super().__init__(**kwargs)
class Two:
def __init__(self, city, **kwargs):
self.city = city
super().__init__(**kwargs)
class Three(One,Two):
def __init__(self, country, address, phone, city, **kwargs):
self.country = country
super().__init__(address=address, phone=phone, city=city, **kwargs)
print(f"{address}, " + f"{phone}, " + f"{self.city}, " + f"{self.country}")
i = Three("Acountry", "AnAddress", "Aphone", "Acity")
Upvotes: 3