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') |
您可以循环访问
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') |
旁注:永远不要使用