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

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

有什么办法可以更改A.keywords<thing B derives from>.keywords,有点像super(),但是 pre- __init__/self?我不喜欢在定义中重复类名。

用法:

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

4 回答 4

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'))
于 2012-04-12T07:36:36.027 回答
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')
于 2012-04-12T07:33:06.120 回答
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()
于 2012-04-12T07:34:22.040 回答
0

我找到了一种解决方法风格的解决方案,无需额外的类和定义即可为我工作。

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

以及子类化时

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

希望这可以帮助。

于 2015-04-16T05:03:20.867 回答