gpt4 book ai didi

python - 如何调用右侧定义的类中存在的方法。 Python继承。多重继承。 Dimond场景python继承

转载 作者:太空宇宙 更新时间:2023-11-03 14:26:26 25 4
gpt4 key购买 nike

我有一个类,它是从其他两个类继承的。当我从子类调用方法时,它总是调用类定义中左侧提到的方法。

我知道Python是这样工作的。它首先检查左侧类中的方法,然后检查右侧类中的方法。

但现在我无法更改我的子类定义。请给我一些帮助,我如何调用“第二”类中存在的相同方法。

我对 Python 有点陌生。使用Python 2.7

class First(object):
def get_details(self):
print "This method gets called every time"
print "I can't change my Child class structure"

class Second(object):
def get_details(self):
print "But I want to call the same method of this class.. "
print "Please let me know what can I do? How do I call method of second inherited class"

class Child(First, Second):
pass


child_obj = Child()
child_obj.get_details()

最佳答案

您可以直接调用它:

Second.get_details(child_obj)

或使用.mro()获取方法解析顺序并选择第二个父级:

Child.mro()[2].get_details(child_obj)

方法解析顺序显示 Python 用于查找方法的类的搜索顺序:

>>> Child.mro()
[__main__.Child, __main__.First, __main__.Second, object]

一旦在此列表中找到get_details(),它就会停止并使用它。

我建议将此逻辑隐藏在 Child 的方法中:

class Child(First, Second):

def get_details_second_1(self):
"""Option 1"""
return Second.get_details(self)

def get_details_second_2(self):
"""Option 2"""
return Child.mro()[2].get_details(self)

child_obj = Child()
child_obj.get_details_second_1()
child_obj.get_details_second_2()

关于python - 如何调用右侧定义的类中存在的方法。 Python继承。多重继承。 Dimond场景python继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47617924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com