|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
编写一个 Counter 类,用于实时检测对象有多少个属性
这是小甲鱼答案
- class Counter(object):
- k = []
- def __init__(self):
- self.counter = 0
- def __setattr__(self,name,value):
- if name != 'counter':
- if name not in self.k:
- self.counter += 1
- print(f"set:{self.counter}")#这个f很有用!!!
- self.k.append(name)
- super().__setattr__(name,value)
- def __delattr__(self,name):
- if name in self.k:
- self.counter -= 1
- print(f"del:{self.counter}")
- self.k.remove(name)
- super().__delattr__(name)
复制代码
这是我的
- class Co:
- def __init__(self):
- self.counter = 0
- def __setattr__(self,name,value):
- # if name != 'counter':这句没有会报错
- self.counter += 1
- super().__setattr__(name,value)
- def __delattr__(self,name):
- self.counter -= 1
- super().__delattr__(name)
复制代码
如果我不用if的话 会报错
AttributeError: 'Co' object has no attribute 'counter'
为什么会用了if 就可以,没用就报错??
因为在__init__()函数中执行self.counter = 0时,会自动调用__setattr__()方法,执行self.counter += 1
而此时self.counter = 0还没有执行完毕,Python发现self没有counter这个属性,因此报错
|
|