gpt4 book ai didi

python - 通过 Mixin 调用 Grandparent Method 而不执行父方法

转载 作者:太空宇宙 更新时间:2023-11-04 05:24:21 25 4
gpt4 key购买 nike

我需要覆盖Parent 方法并通过mixin 调用Grandparent 方法。是否可以?

例如:AB 是库类。

class A(object):
def class_name(self):
print "A"


class B(A):
def class_name(self):
print "B"
super(B, self).class_name()
# other methods ...

现在我需要重写 Bclass_name 方法并将其称为 super。

class Mixin(object):
def class_name(self):
print "Mixin"
# need to call Grandparent class_name instead of parent's
# super(Mixin, self).class_name()


class D(Mixin, B):
# Here I need to override class_name method from B and call B's super i.e. A's class_name,
# It is better if I can able to do this thourgh Mixin class. (
pass

现在当我调用 D().class_name() 时,它应该只打印 "Mixin"和 "A"。不是“B”

最佳答案

一种方法是使用 inspect.getmro()但如果用户编写 class D(B, Mixin),这可能会中断。

让我演示一下:

class A(object):
def class_name(self):
print "A"


class B(A):
def class_name(self):
print "B"
super(B, self).class_name()
# other methods ...

class Mixin(object):
def class_name(self):
print "Mixin"
# need to call Grandparent class_name instead of parent's
# super(Mixin, self).class_name()


class D(Mixin, B):
# Here I need to override class_name method from B and call B's super i.e. A's class_name,
# It is better if I can able to do this thourgh Mixin class. (
pass

class E(B, Mixin): pass


import inspect
print inspect.getmro(D) # returns tuple with (D, Mixin, B, A, object)
print inspect.getmro(E) # returns tuple with (E, B, A, Mixin, object)

所以如果你有控制权并且可以确保你总是首先得到Mixin。您可以使用 getmro() 获取祖 parent 并执行它的 class_name 函数。

关于python - 通过 Mixin 调用 Grandparent Method 而不执行父方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39331875/

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