基类:
class BaseTest():
m_list = ['a', 'b']
我想让每个BaseTest实例并通过装饰器修改其成员变量,因为我不想更改BaseTest的代码,因为
m_list = ['a', 'b', 'c']
然后下一次:
test = BaseTest()
print test.m_list
#Output: ['a', 'b', 'c']
我该如何实施?
答案 0 :(得分:2)
def dec(cls):
cls.m_list = ['a', 'b', 'c']
return cls
@dec
class BaseTest():
m_list = ['a', 'b']
答案 1 :(得分:0)
# here you have a class
class BaseTest():
m_list = ['a', 'b']
quantity=12345
# here you extending from existing class
class BaseTestextended(BaseTest):
m_list = ['a', 'b','c']
bte= BaseTestExtended()
bte.mlist # outputs ['a','b','c']
bte.quantity # outputs 12345
如果你想通过函数返回修改的params对象,你可以这样做:
class BaseTestextended(BaseTest):
@classmethod
def mlist(self):
return m_list.append('c')