oneface 发表于 2020-11-9 23:33:50

关于__delattr__ 魔法的疑问

class C:
    counter = 0
   
    def __setattr__(self,name,value):
      C.counter += 1
      super().__setattr__(name,value)

    def __delattr__(self,nanme):
      C.counter -= 1
      super().__delattr__(name)

a =C()
a.x=1
del a.x

Traceback (most recent call last):
File "<pyshell#52>", line 1, in <module>
    del a.x
File "E:/45-0.py", line 10, in __delattr__
    super().__delattr__(name)
NameError: name 'name' is not defined

为什么'name'未定义呢,这里不应该已经定义了吗

oneface 发表于 2020-11-9 23:39:43

再补充一下,用的python 3.9.0是不是在这个版本__delattr__方法已经不需要传入name参数了

oneface 发表于 2020-11-9 23:40:18

>>> help(a.__delattr__)
Help on method __delattr__ in module __main__:

__delattr__(nanme) method of __main__.C instance
    Implement delattr(self, name).

oneface 发表于 2020-11-9 23:40:52

oneface 发表于 2020-11-9 23:40
>>> help(a.__delattr__)
Help on method __delattr__ in module __main__:



还是要的,那为什么会报错呢

altf11 发表于 2020-11-10 00:08:20

def __delattr__(self,name) 这一行,name你多打了个n {:10_266:}

oneface 发表于 2020-11-10 10:11:24

altf11 发表于 2020-11-10 00:08
def __delattr__(self,name) 这一行,name你多打了个n

我傻了,我是瞎子{:10_266:}
页: [1]
查看完整版本: 关于__delattr__ 魔法的疑问