0

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

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

4

2 回答 2

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()

你可以做一些棘手的事情来让它更加自动化,但我认为你不想这样做。(如果您认为需要,请先阅读描述符或元类的工作原理,然后再提出具体问题。)

于 2012-12-13T20:59:30.003 回答
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]
于 2012-12-13T20:59:32.287 回答