鱼C论坛

 找回密码
 立即注册
查看: 987|回复: 2

关于零基础python45讲课后习题第二题方法

[复制链接]
发表于 2020-4-9 14:27:42 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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'

所以我就改了改代码:
  1. class Counter:
  2.     def __init__(self):
  3.         super().__setattr__("counter",0)
  4.     def __getattribute__(self,name):
  5.         #print("找到该属性啦!")
  6.         try:
  7.             return super().__getattribute__(name)
  8.         except AttributeError as reason:
  9.              print("没有这个属性!")
  10.             
  11.     #def __getattr__(self,name):
  12.         #if hasattr(self,name) == False:
  13.         #print("该属性不存在!")
  14.         #return False
  15.             

  16.     def __setattr__(self,name,value):
  17.         if name != "counter":
  18.             super().__setattr__(name,value)
  19.             super().__setattr__("counter",self.counter+1)
  20.         #elif name == "counter":
  21.             #super().__setattr__("counter",0)

  22.     def __delattr__(self,name):
  23.         #print("delattr")
  24.         try:
  25.             if name != "counter" and hasattr(self,name) == True:
  26.                 super().__delattr__(name)
  27.                 super().__setattr__("counter",self.counter-1)
  28.         except AttributeError as reason:
  29.             print("没有这个属性!")
复制代码


不过这样写感觉有点奇怪所以想请教大家有没有更好的办法谢谢啦
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2020-4-9 16:25:29 | 显示全部楼层
没人吗
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-4-9 17:23:31 | 显示全部楼层
  1.             if name != "counter" and hasattr(self, name) == True:
  2.                 super().__delattr__(name)
  3.                 super().__setattr__("counter", self.counter - 1)
复制代码


这里可以简化,把 hasattr(self, name) == True 改为 hasattr(self, name) 也可以
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-4-22 07:41

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表