Python类属性可以添加吗?

时间:2012-12-13 20:55:13

标签: python list inheritance

我有一个具有以下类结构的项目:

class A(object):
    elems = [1, 2, 3]

class B(A):
    pass

class C(B):
    elems = [20, 100]

class D(B):
    elems = [4, 5]

目前,Python的默认继承行为是在每个后​​续属性声明中覆盖elems属性,例如:

A.elems == [1, 2, 3]
B.elems == [1, 2, 3]
C.elems == [20, 100]
D.elems == [4, 5]

我希望能够访问这些值的添加列表。换句话说,我希望能够检索以下列表:

A.collated() == [1, 2, 3]
B.collated() == [1, 2, 3]
C.collated() == [1, 2, 3, 20, 100]
D.collated() == [1, 2, 3, 4, 5]

我不知道该怎么做。任何帮助将不胜感激。

提前致谢,
- B

2 个答案:

答案 0 :(得分:5)

这里最简单的解决方案是明确:

class A(object):
    elems = [1, 2, 3]
    @classmethod
    def collated(cls):
      return sorted(cls.elems)

class B(A):
    pass

class C(B):
    elems = B.elems + [20, 100]

class D(B):
    elems = B.elems + [4, 5]

print "A.collated() == ", A.collated()
print "B.collated() == ", B.collated()
print "C.collated() == ", C.collated()
print "D.collated() == ", D.collated()

你可以做 棘手的事情来使这更加自动,但我认为你不想这样做。 (如果您认为自己想要,请先阅读描述符或元类的工作方式,然后再回答具体问题。)

答案 1 :(得分:3)

只需明确并访问要扩展的父级的类实例...

class A(object):
    elems = [1, 2, 3]

class B(A):
    elems = A.elems # or pass

class C(B):
    elems = B.elems + [20, 100]

class D(B):
    elems = B.elems + [4, 5]

print A.elems, B.elems, C.elems, D.elems
# [1, 2, 3] [1, 2, 3] [1, 2, 3, 20, 100] [1, 2, 3, 4, 5]