关于python:通过继承连接类变量?

Concatenate class variable through inheritance?

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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__元组:

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

演示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
>>> 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()调用原始方法,这将导致无限递归,请参阅如何使用super()避免无限递归?。请改用super(ClassName, self)或(仅限python 3)super()