gpt4 book ai didi

python - 在实例方法中从父级访问类属性

转载 作者:行者123 更新时间:2023-11-28 21:35:10 25 4
gpt4 key购买 nike

我想从类继承链上的每个类中读取类属性。

类似于以下内容:

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 的菱形形状),可以获得奖励积分。

最佳答案

我想你可以手动内省(introspection)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

或者也许按相反的顺序:

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]

关于python - 在实例方法中从父级访问类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52532937/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com