鱼C论坛

 找回密码
 立即注册
查看: 1663|回复: 3

课时45,课后练习第三题

[复制链接]
发表于 2021-8-23 17:22:24 | 显示全部楼层 |阅读模式

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

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

x
3\在不上机验证的情况下,你能推断以下代码分别会显示什么吗?
  1. class C:
  2.         def __getattr__(self, name):
  3.                 print(1)
  4.                 return super().__getattr__(name)
  5.         def __getattribute__(self, name):
  6.                 print(2)
  7.                 return super().__getattribute__(name)
  8.         def __setattr__(self, name, value):
  9.                 print(3)
  10.                 super().__setattr__(name, value)
  11.         def __delattr__(self, name):
  12.                 print(4)
  13.                 super().__delattr__(name)
复制代码
  1. >>> c = C()
  2. >>> c.x
  3. 2
  4. 1
  5. Traceback (most recent call last):
  6.   File "<pyshell#31>", line 1, in <module>
  7.     c.x
  8.   File "<pyshell#29>", line 4, in __getattr__
  9.     return super().__getattr__(name)
  10. AttributeError: 'super' object has no attribute '__getattr__'
复制代码

答案中是这么解释:
为什么会如此显示呢?我们来分析下:首先 c.x 会先调用 __getattribute__() 魔法方法,打印 2;然后调用 super().__getattribute__(),找不到属性名 x,因此会紧接着调用 __getattr__() ,于是打印 1;但是你猜到了开头没猜到结局……当你希望最后以 super().__getattr__() 终了的时候,Python 竟然告诉你 AttributeError,super 对象木有 __getattr__ !!
求证:
  1. >>> dir(super)
  2. ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__self_class__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__thisclass__']
复制代码



问题来了~没明白的是C类默认继承的不都是Object类吗?和super有没有__getattr__有什么关系呢?。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2021-8-23 17:38:54 | 显示全部楼层
super != super()
你在类里面打印一下 dir(super())看看就知道了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2021-8-23 18:38:25 | 显示全部楼层
qiuyouzhi 发表于 2021-8-23 17:38
super != super()
你在类里面打印一下 dir(super())看看就知道了

没明白的是C类默认继承的不都是Object类吗?和super()有没有__getattr__有什么关系呢?。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2021-8-23 18:41:50 | 显示全部楼层
非凡 发表于 2021-8-23 18:38
没明白的是C类默认继承的不都是Object类吗?和super()有没有__getattr__有什么关系呢?。


也没说它俩有啥关系呀
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-6-19 15:46

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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