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

时间:2012-04-12 07:25:50

标签: python class-variables

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

class B (A):
    keywords = A.keywords + ('four', 'five', 'six')

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

用法:

>>> A.keywords
('one', 'two', 'three')
>>> B.keywords
('one', 'two', 'three', 'four', 'five', 'six')

4 个答案:

答案 0 :(得分:5)

实际上,你可以。编写一个descriptor来检查类的基础,查找具有相同名称的属性,并将传递的属性添加到其值中。

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

答案 1 :(得分:1)

是。只要你已经开始上课,就使用__bases__ attr查找基类。否则你需要改变方法,因为B不知道它的父母。

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

class B (A):
    def __init__(self):
        keywords = self.__bases__[0].keywords + ('four', 'five', 'six')

答案 2 :(得分:1)

使用元类:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

class Meta(type):
    def __new__(cls, name, bases, attrs):
        new_cls = super(Meta,cls).__new__(cls, name, bases, attrs)
        if hasattr(new_cls, 'keywords'):
            new_cls.keywords += ('1','2')
        return new_cls

class B(object):
    keywords = ('0',)
    __metaclass__= Meta

def main():
    print B().keywords

if __name__ == '__main__':
    main()

答案 3 :(得分:0)

我发现了一种解决方法式解决方案,无需额外的类和defs就能为我工作。

class BaseModelAdmin(admin.ModelAdmin):
    _readonly_fields = readonly_fields = ('created_by', 'date_add', 'date_upd', 'deleted')

和子类化时

class PayerInline(BaseTabularInline):
    exclude = BaseTabularInline._exclude + ('details',)

希望这有帮助。