我的目标:在子类中创建名为 [identify2] 的方法,该方法从 Parent2 类调用 [identify] 方法。这必须使用 super() 关键字来完成。
我的问题:两个父类中的方法名称相同。但我只想涉及使用 super() 关键字的parent2 类的方法。我该怎么办?
class Parent1:
def identify(self):
return "This method is called from Parent1"
class Parent2:
def identify(self):
return "This method is called from Parent2"
# declare child class here
class child(Parent1, Parent2):
def identify(self):
return "This method is called from Child"
def identify2(self):
super().identify() # I want to call the method of Parent2 class, how?
child_object = child()
# Expected output:
print( child_object.identify() ) # This method is called from Child
print( child_object.identify2() ) # This method is called from Parent2
最佳答案
super
可以使用类型和对象参数进行调用,请参阅 documentation 。类型参数确定在 mro 顺序中的哪个类之后开始搜索方法。在本例中,要获取 Parent2
的方法,搜索应在 Parent1
之后开始:
class Parent1:
def identify(self):
return "This method is called from Parent1"
class Parent2:
def identify(self):
return "This method is called from Parent2"
# declare child class here
class Child(Parent1, Parent2):
def identify(self):
return "This method is called from Child"
def identify2(self):
return super(Parent1, self).identify()
child_object = Child()
# Expected output:
print( child_object.identify() ) # This method is called from Child
print( child_object.identify2() ) # This method is called from Parent2
这给出:
This method is called from Child
This method is called from Parent2
关于python - 如何在Python中的super()函数中指定使用哪个父类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69732726/