Edit: Thanks for the replies. This is a practice exercise from a website that I'm using to learn, I haven't designed it. I want to confirm that the Wolf.action(self) is an static call and ask why would you make Wolf inherit from Animal if you can only use Dog Class' methods with super() due to MRO (in Diamond scheme). Is there any point on making a subclass inherit from several independent classes since you can only use super() with the first one listed in the definition? Does it have anything to do with imports?
So, in this code:
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def action(self):
print("{} wags tail. Awwww".format(self.name))
class Wolf(Animal):
def action(self):
print("{} bites. OUCH!".format(self.name))
class Hybrid(Dog, Wolf):
def action(self):
super().action()
Wolf.action(self)
my_pet = Hybrid("Fluffy")
my_pet.action() # Fluffy wags tail. Awwww
# Fluffy bites. OUCH!
Why do I have to provide self
in Wolf.action(self)
but not in super().action()
?
Why can't I just do Wolf.action()
?
I'm guessing this is just an static call, and thus that's why I need to pass an explicit parameter. But then, what is the point of multi inheritance in this context? Wouldn't it be the same if Hybrid
doesn't inherit from Wolf
?
I've read some other threads but the majority of them talk about MRO and that is not the answer I'm looking for.
Thanks in advance.
CodePudding user response:
Wolf.action
is the actual function, not a bound method that implicitly includes self
when you try to call it.
However, if you use super
properly, you don't need an explicit call to Wolf.action
.
class Animal:
def __init__(self, name):
self.name = name
def action(self):
pass
class Dog(Animal):
def action(self):
super().action()
print("{} wags tail. Awwww".format(self.name))
class Wolf(Animal):
def action(self):
super().action()
print("{} bites. OUCH!".format(self.name))
class Hybrid(Wolf, Dog):
pass
my_pet = Hybrid("Fluffy")
my_pet.action() # Fluffy wags tail. Awwww
# Fluffy bites. OUCH!