我试图通过继承隐式连接类变量。我能够上升一级而不是更多......这实际上可能吗?
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')
答案 0 :(得分:3)
您可以遍历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()
。