|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
根据鱼哥的视频讲解,还是对__getattribute__这个魔法方法有点不了解 ,只是大致明白简单的用法
根据以下代码提出疑问
- >>> class C:
- def __getattribute__(self,name):
- print('getattribute')
- return super().__getattribute__(name)
- def __getattr__(self,name):
- print('getattr')
- def __setattr__(self,name,value):
- print('setattr')
- super().__setattr__(name,value)
- def __delattr__(self,name):
- print('delattr')
- super().__delattr__(name)
-
- >>> c = C()
- >>> c.x
- getattribute
- getattr
- >>> c.x = 1
- setattr
- >>> c.x
- getattribute
- 1
- >>> del c.x
- delattr
复制代码
代码中的:
- def __getattribute__(self,name):
- print('getattribute')
- return super().__getattribute__(name)
复制代码
__getattribute__魔法方法是在调用属性的时候执行的,但是调用属性执行后打印了'getattribute',但是return返回的内容在去找到object的__getattribute__魔法方法参数为name,这里是干什么用的呢
然后我自己写了一段代码,执行起来不对劲,参考如下:
- >>> class C:
- def __getattribute__(self,name):
- print('getattribute')
- def __getattr__(self,name):
- print('getattr')
-
- >>> c = C()
- >>> c.x
- getattribute
复制代码
为什么访问不存在的属性__getattr__魔法方法没有执行呢
因为 __getattribute__ 魔法方法会在你访问属性时候自动调用,而当找不到这个属性时候就会引发报错
但是如果有设置 __getattr__ 魔法方法那么这个魔法方法就会捕获这个错误,返回 __getattr__ 设置的返回值
而你的代码重写了 __getattribute__ 魔法方法,但是没有调用父类的 __getattribute__ 导致失去了原有的功能
而且你重写的 __getattribute__ 魔法方法,也只有 print('getattribute') 这一个功能,其他毫无作用了,所以就不会引发报错,也不会导致触发 __getattr__ 了
|
|