[英]Python - appending to class-level lists in derived class definitions
class A (object):
keywords = ('one', 'two', 'three')
class B (A):
keywords = A.keywords + ('four', 'five', 'six')
有什么辦法可以將A.keywords
更改為<thing B derives from>.keywords
,有點像super()
,但是<thing B derives from>.keywords
__init__/self
? 我不喜歡在定義中重復類名。
用法:
>>> A.keywords
('one', 'two', 'three')
>>> B.keywords
('one', 'two', 'three', 'four', 'five', 'six')
實際上,你可以。 編寫一個描述符 ,檢查類的基礎是否具有相同名稱的屬性,並將傳遞的屬性添加到其值。
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'))
是。 只要已初始化類,請使用__bases__ attr查找基類。 否則,由於B不了解其父母,因此您需要更改方法。
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()
我發現了一種無需其他類和定義即可使用的變通方式樣式的解決方案。
class BaseModelAdmin(admin.ModelAdmin):
_readonly_fields = readonly_fields = ('created_by', 'date_add', 'date_upd', 'deleted')
當子類化時
class PayerInline(BaseTabularInline):
exclude = BaseTabularInline._exclude + ('details',)
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.