在实例方法中从父级访问类属性 [英] Accessing class attributes from parents in instance methods
问题描述
我想从类继承链中的每个类中读取类属性.
I would like to read class attributes from each class all the way up the class inheritance chain.
类似以下内容:
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
属性?
Obviously, each words
attribute is overriding the others, as it should. How can I do something similar that will let me read the words
attribute from each class in the inheritance chain?
有没有更好的方法可以解决这个问题?
Is there a better way I can approach this problem?
奖励指向可以与多个继承链配合使用的事物(呈菱形,并且所有内容最终都继承自Base
).
Bonus points for something that will work with multiple inheritance chains (in a diamond shape with everything inheriting from Base
in the end).
推荐答案
我想您可以手动对mro
进行内部检查,效果如下:
I guess you could introspect the mro
manually, something to the effect of:
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]
这篇关于在实例方法中从父级访问类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!