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')
最佳答案
实际上,你可以。编写一个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'))
关于python - Python-在派生类定义中追加到类级别列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10119233/