joelau 发表于 2020-4-9 14:27:42

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

在小甲鱼的例程代码中我发现它有个不人性化的地方
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("没有这个属性!")

不过这样写感觉有点奇怪所以想请教大家有没有更好的办法谢谢啦

joelau 发表于 2020-4-9 16:25:29

没人吗

zltzlt 发表于 2020-4-9 17:23:31

            if name != "counter" and hasattr(self, name) == True:
                super().__delattr__(name)
                super().__setattr__("counter", self.counter - 1)

这里可以简化,把 hasattr(self, name) == True 改为 hasattr(self, name) 也可以
页: [1]
查看完整版本: 关于零基础python45讲课后习题第二题方法