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

Python-附加到派生类定义中的类级列表,python,class-variables,Python,Class Variables,有没有办法将A.keywords更改为.keywords,有点像super(),但是在\uuuuuuuu\uuuuuuu/self之前?我不喜欢在定义中重复类名 用法: class A (object): keywords = ('one', 'two', 'three') class B (A): keywords = A.keywords + ('four', 'five', 'six') 对。只要您已经初始化了类,就可以使用_base __属性来查找基类。否则,您需要改

有没有办法将
A.keywords
更改为
.keywords
,有点像
super()
,但是在
\uuuuuuuu\uuuuuuu/self
之前?我不喜欢在定义中重复类名

用法:

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

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

对。只要您已经初始化了类,就可以使用_base __属性来查找基类。否则,您需要改变方法,因为B不知道它的父对象

>>> A.keywords
('one', 'two', 'three')
>>> B.keywords
('one', 'two', 'three', 'four', 'five', 'six')
使用元类:

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

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

事实上,你可以。编写一个函数,检查类的基是否有同名的属性,并将传递的属性添加到其值中

#!/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()

我发现一个变通方式的解决方案适合我,不需要额外的类和def

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'))
当子类化时

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

希望这能有所帮助。

虽然这是我看到的唯一一种不用按名称调用任何类的方法,但它似乎与问题不成比例。没错,agf。这是很好的信息,但我正在寻找一个很小的解决方案,比如super()。关键字+关键字。谢谢。问题的重点是如何在类定义时执行。@GaryFixler afg是正确的,使用Ignatio方法,我的方法在基本级别上根本不起作用。明白。是的,我在类级别需要这个,pre-instance.interest。我还没有想到要找一个更外部的地方来解决这个问题。
class PayerInline(BaseTabularInline):
    exclude = BaseTabularInline._exclude + ('details',)