python魔法方法45讲
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__=counter+1
return super().__setattr__(name,counter)
def __delattr__(self,name):
self.__dict__=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) isdkz 发表于 2023-2-5 13:33
因为 name 是赋值的那个属性,而不是 counter 属性,还有不用 self.counter 的话获取的不是 counter 属性的 ...
奥,对了,就和第一题那个结果一样
页:
[1]