python类属性

gbu*_*ler 10 python variables class

我正在尝试找到扩展类变量的最佳方法.希望到目前为止我提出的方法的一个例子将清楚地说明这一点.

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

class B(A):
    foo = A.foo + ['stuff', 'more stuff']
Run Code Online (Sandbox Code Playgroud)

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

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

Sil*_*Ray 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']
Run Code Online (Sandbox Code Playgroud)

  • 很好,但违反了最少惊喜的原则.也许分配给`__add_to_foo__`,假装我们从`object`继承了一个空的`foo`. (2认同)