我正在尝试找到扩展类变量的最佳方法。希望到目前为止我提出的方法的一个例子将清楚地说明这一点。
class A(object):
foo = ['thing', 'another thing']
class B(A):
foo = A.foo + ['stuff', 'more stuff']
所以我试图让子类继承并扩展父类的变量。上面的方法有效,但似乎有些笨拙。我愿意接受任何建议,包括使用完全不同的方法完成类似的事情。
显然,如果需要,我可以继续使用这种方法,但是如果有更好的方法我想找到它。
答案 0 :(得分:8)
可以使用元类:
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']
答案 1 :(得分:1)
我明确地会选择例如属性。 (如果我做对了,你的情况不一定是静态的吗?!)
>>> class A:
... @property
... def foo(self):
... return ['thin', 'another thing']
...
>>> class B(A):
... @property
... def foo(self):
... return super().foo + ['stuff', 'thing 3']
...
>>> B().foo
['thin', 'another thing', 'stuff', 'thing 3']