python类属性 [英] python class properties

查看:111
本文介绍了python类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到扩展类变量的最好方法。希望我到目前为止所提出的方法的一个例子将使这个清楚。

I'm trying to find the best way to extend a class variable. Hopefully an example of the method I've come up with so far will make this clear.

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

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

所以我试图让子类继承和扩展父类的变量。上面的方法工作,但似乎有点kludgey。我对任何建议,包括使用完全不同的方法完成类似的东西,开放。

So I'm trying to make the subclass inherit and extend the parent's class variable. The method above works, but seems a bit kludgey. I'm open to any suggestion, including accomplishing something similar using a completely different approach.

显然,如果需要,我可以继续使用这种方法,但如果有一个更好

Obviously I can continue to use this method if need be, but if there's a better way I'd like to find it.

推荐答案

可以使用元类:

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']

这篇关于python类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆