可以使用元类:
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