【发布时间】:2019-12-17 09:14:35
【问题描述】:
我正在使用一个我无法控制的类 (MainClass)。我想以 MainClass 为基础,但要添加额外的功能。我已经向我的类(SuperClass)添加了一个属性(索引),但是当我尝试将索引转换为属性时,@.setter 似乎被忽略了。这里有什么问题?
class MainClass(object):
def __init__(self):
self.name = 'abc'
class SuperClass(object):
def __init__(self, main, *args, **kwargs):
super(SuperClass, self).__init__(*args, **kwargs)
self.__main = main
self._index = 0
def __getattr__(self, attr):
return getattr(self.__main, attr)
def __setattr__(self, attr, val):
if attr == '_SuperClass__main':
object.__setattr__(self, attr, val)
return setattr(self.__main, attr, val)
@property
def index(self):
return self._index
@index.setter
def index(self, value):
self._index = value
main_object = MainClass()
super_object = SuperClass(main_object)
print('x', super_object.index, super_object.name)
super_object.index = 3
print('y', super_object.index)
super_object.index += 2
print('z', super_object.index)
【问题讨论】:
-
您是否有理由不让
SuperClass继承自Main?
标签: python oop properties