如何在 python 的 super( ) 函数中指定使用哪个父 class?
How to specify which parent class to use in super( ) function in python?
My Objective:在子 class 中创建名为 [identify2] 的方法,该方法从 Parent2 class 调用 [identify] 方法。这必须使用 super() 关键字来完成。
我的问题:两个父 class 中的方法名称相同。但我只想使用 super() 关键字与 parent2 class 的方法有关。我该怎么办?
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 顺序中的 class 之后将开始搜索方法。在这种情况下,要获得 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
My Objective:在子 class 中创建名为 [identify2] 的方法,该方法从 Parent2 class 调用 [identify] 方法。这必须使用 super() 关键字来完成。
我的问题:两个父 class 中的方法名称相同。但我只想使用 super() 关键字与 parent2 class 的方法有关。我该怎么办?
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 顺序中的 class 之后将开始搜索方法。在这种情况下,要获得 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