Python - 在派生类定义中附加到类级别列表

Gar*_*ler 2 python class-variables

class A (object):
    keywords = ('one', 'two', 'three')

class B (A):
    keywords = A.keywords + ('four', 'five', 'six')
Run Code Online (Sandbox Code Playgroud)

有没有什么办法改变A.keywords<thing B derives from>.keywords,有点像super(),但预__init__/self?我不喜欢在定义中重复类名.

用法:

>>> A.keywords
('one', 'two', 'three')
>>> B.keywords
('one', 'two', 'three', 'four', 'five', 'six')
Run Code Online (Sandbox Code Playgroud)

Ign*_*ams 5

实际上,你可以.编写一个描述符,用于检查具有相同名称的属性的类的基础,并将传递的属性添加到其值中.

class parentplus(object):
    def __init__(self, name, current):
        self.name = name
        self.value = current

    def __get__(self, instance, owner):
        # Find the attribute in self.name in instance's bases
        # Implementation left as an exercise for the reader

class A(object):
    keywords = ('one', 'two', 'three')

class B(A):
    keywords = parentplus('keywords', ('four', 'five', 'six'))
Run Code Online (Sandbox Code Playgroud)