10

我试图找到扩展类变量的最佳方法。希望到目前为止我提出的方法的一个例子可以说明这一点。

class A(object):
    foo = ['thing', 'another thing']

class B(A):
    foo = A.foo + ['stuff', 'more stuff']

所以我试图让子类继承并扩展父类的类变量。上面的方法有效,但似乎有点笨拙。我愿意接受任何建议,包括使用完全不同的方法完成类似的事情。

显然,如果需要,我可以继续使用这种方法,但如果有更好的方法,我想找到它。

4

2 回答 2

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']
于 2012-07-26T19:26:06.953 回答
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']
于 2012-07-26T20:27:08.800 回答