gpt4 book ai didi

python - 通过继承连接类变量?

转载 作者:行者123 更新时间:2023-11-30 22:55:10 25 4
gpt4 key购买 nike

我试图通过继承隐式连接类变量。我能够升一级,但不能升更多……这真的可能吗?

class Base(object):
def get_crumbs(self):
crumbs = getattr(super(self.__class__, self), 'crumbs', ())
crumbs += getattr(self, 'crumbs', ())
return crumbs


class A(Base):
crumbs = ('un chasseur', )


class B(A):
crumbs = ('sachant chasser', )


class C(B):
crumbs = ('sans son chien', 'est un bon chasseur')


>>> c = C()
>>> c.get_crumbs()
>>> <type 'tuple'>: ('sachant chasser', 'sans son chien', 'est un bon chasseur')

最佳答案

您可以循环class.__mro__ tuple :

class Base(object):
def get_crumbs(self):
crumbs = []
for cls in type(self).__mro__:
crumbs.extend(getattr(cls, 'crumbs', ()))
return tuple(crumbs)

演示:

>>> class Base(object):
... def get_crumbs(self):
... crumbs = []
... for cls in type(self).__mro__:
... crumbs.extend(getattr(cls, 'crumbs', ()))
... return tuple(crumbs)
...
>>> class A(Base):
... crumbs = ('un chasseur',)
...
>>> class B(A):
... crumbs = ('sachant chasser',)
...
>>> class C(B):
... crumbs = ('sans son chien', 'est un bon chasseur')
...
>>> c = C()
>>> c.get_crumbs()
('sans son chien', 'est un bon chasseur', 'sachant chasser', 'un chasseur')

旁注:永远不要使用 super(self.__class__, self)。如果您重写 get_crumbs() 方法并使用 super() 调用原始方法,这将导致无限递归,请参阅 How to avoid infinite recursion with super()? 。请改用 super(ClassName, self) 或(仅限 Python 3)super()

关于python - 通过继承连接类变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37488041/

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