|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
在小甲鱼的例程代码中我发现它有个不人性化的地方
del一个本身就没有存在的属性时会出现错误:
>>> del a.b
Traceback (most recent call last):
File "<pyshell#256>", line 1, in <module>
del a.b
File "D:\学习\python\自编\小甲鱼\编写一个 Counter 类,用于实时检测对象有多少个属性.py", line 42, in __delattr__
super().__delattr__(name)
AttributeError: b
当我把counter删除掉的时候,我觉得不应该可以删除counter:
>>> del a.counter
>>> a.counter
Traceback (most recent call last):
File "<pyshell#258>", line 1, in <module>
a.counter
AttributeError: 'Counter' object has no attribute 'counter'
所以我就改了改代码:
- class Counter:
- def __init__(self):
- super().__setattr__("counter",0)
- def __getattribute__(self,name):
- #print("找到该属性啦!")
- try:
- return super().__getattribute__(name)
- except AttributeError as reason:
- print("没有这个属性!")
-
- #def __getattr__(self,name):
- #if hasattr(self,name) == False:
- #print("该属性不存在!")
- #return False
-
- def __setattr__(self,name,value):
- if name != "counter":
- super().__setattr__(name,value)
- super().__setattr__("counter",self.counter+1)
- #elif name == "counter":
- #super().__setattr__("counter",0)
- def __delattr__(self,name):
- #print("delattr")
- try:
- if name != "counter" and hasattr(self,name) == True:
- super().__delattr__(name)
- super().__setattr__("counter",self.counter-1)
- except AttributeError as reason:
- print("没有这个属性!")
复制代码
不过这样写感觉有点奇怪所以想请教大家有没有更好的办法谢谢啦 |
|