可以使用元類:
class AutoExtendingFoo(type):
def __new__(cls, name, bases, attrs):
foo = []
for base in bases:
try:
foo.extend(getattr(base, 'foo'))
except AttributeError:
pass
try:
foo.extend(attrs.pop('foo_additions'))
except KeyError:
pass
attrs['foo'] = foo
return type.__new__(cls, name, bases, attrs)
class A(object):
__metaclass__ = AutoExtendingFoo
foo_additions = ['thing1', 'thing2']
# will have A.foo = ['thing1', 'thing2']
class B(A):
foo_additions = ['thing3', 'thing4']
# will have B.foo = ['thing1', 'thing2', 'thing3', 'thing4']
class C(A):
pass
# will have C.foo = ['thing1', 'thing2']
class D(B):
pass
# will have D.foo = ['thing1', 'thing2', 'thing3', 'thing4']
是什麼樣的'foo',它需要一個[類屬性(HTTP:// stackoverflow.com/questions/128573/)而不只是一個實例屬性? (對於這個問題,考慮到列表是可變的,你可以在'__init__'時間改變*類屬性。) – kojiro 2012-07-26 18:41:15
恕我直言,你對我看起來很好(我想不出一個更乾淨的方式來做它)。順便說一句,我會稱這些「類屬性」,而不是「類屬性」,因爲屬性是不同的東西(通常由'property'內建函數/裝飾器創建)。 – mgilson 2012-07-26 18:41:35
@kojiro他不是指那些屬性,他只是指屬性。 – Julian 2012-07-26 18:52:18