|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
45讲最后一题
class Counter:
def __init__(self):
super().__setattr__('counter',0)
def __setattr__(self,name,counter):
super().__setattr__('counter',self.counter+1)
return super().__setattr__(name,counter)
def __delattr__(self,name):
super().__setattr__('counter',self.counter-1)
super().__delattr__(name)
红字部分改为:
class Counter:
def __init__(self):
super().__setattr__('counter',0)
def __setattr__(self,name,counter):
self.__dict__[name]=counter+1
return super().__setattr__(name,counter)
def __delattr__(self,name):
self.__dict__[name]=counter-1
super().__delattr__(name)
就像练习中第一题的改法那样,为什么counter不计数呢?
本帖最后由 isdkz 于 2023-2-5 13:34 编辑
因为 name 是赋值的那个属性,而不是 counter 属性,还有不用 self.counter 的话获取的不是 counter 属性的值,而是传进来的参数 counter
class Counter:
def __init__(self):
super().__setattr__('counter',0)
def __setattr__(self,name,counter):
self.__dict__['counter']=self.counter+1
return super().__setattr__(name,counter)
def __delattr__(self,name):
self.__dict__['counter']=self.counter-1
super().__delattr__(name)
|
|