我想从类继承链的各个方面读取每个类的属性。
类似以下内容:
class Base(object):
def smart_word_reader(self):
for word in self.words:
print(word)
class A(Base):
words = ['foo', 'bar']
class B(A):
words = ['baz']
if __name__ == '__main__':
a = A()
a.smart_word_reader() # prints foo, bar as expected
b = B()
b.smart_word_reader() # prints baz - how I can I make it print foo, bar, baz?
很显然,每个words
属性都应该覆盖其他属性。我该如何做类似的事情,让我从继承链中的每个类中读取words
属性?
有没有更好的方法可以解决这个问题?
奖励指向可以与多个继承链配合使用的事物(呈菱形,并且所有内容都从Base
继承)。
答案 0 :(得分:3)
我想您可以手动对mro
进行内部检查,其效果如下:
In [8]: class Base(object):
...: def smart_word_reader(self):
...: for cls in type(self).mro():
...: for word in getattr(cls, 'words', ()):
...: print(word)
...:
...: class A(Base):
...: words = ['foo', 'bar']
...:
...: class B(A):
...: words = ['baz']
...:
In [9]: a = A()
In [10]: a.smart_word_reader()
foo
bar
In [11]: b = B()
In [12]: b.smart_word_reader()
baz
foo
bar
或者以reversed
的顺序:
In [13]: class Base(object):
...: def smart_word_reader(self):
...: for cls in reversed(type(self).mro()):
...: for word in getattr(cls, 'words', ()):
...: print(word)
...:
...: class A(Base):
...: words = ['foo', 'bar']
...:
...: class B(A):
...: words = ['baz']
...:
In [14]: a = A()
In [15]: a.smart_word_reader()
foo
bar
In [16]: b = B()
In [17]: b.smart_word_reader()
foo
bar
baz
或更复杂的模式:
In [21]: class Base(object):
...: def smart_word_reader(self):
...: for cls in reversed(type(self).mro()):
...: for word in getattr(cls, 'words', ()):
...: print(word)
...:
...: class A(Base):
...: words = ['foo', 'bar']
...:
...: class B(Base):
...: words = ['baz']
...:
...: class C(A,B):
...: words = ['fizz','pop']
...:
In [22]: c = C()
In [23]: c.smart_word_reader()
baz
foo
bar
fizz
pop
In [24]: C.mro()
Out[24]: [__main__.C, __main__.A, __main__.B, __main__.Base, object]
答案 1 :(得分:2)
我将smart_word_reader
设为classmethod
,然后在reversed(cls.__mro__)
上进行迭代。
class Base:
@classmethod
def smart_word_reader(cls):
the_words = (word for X in reversed(cls.__mro__)
for word in vars(X).get('words', []))
print('\n'.join(the_words))
演示:
>>> a = A()
>>> b = B()
>>> a.smart_word_reader()
foo
bar
>>> b.smart_word_reader()
foo
bar
baz
修改
细微的错误:我们不希望getattr
(考虑class C(B): pass
)在子类中查找缺少的属性。将getattr
的呼叫更改为vars(X).get('words', [])
。