鱼C论坛

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

零基础45第3题

[复制链接]
发表于 2018-8-20 18:43:29 | 显示全部楼层 |阅读模式

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

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

x
3. 在不上机验证的情况下,你能推断以下代码分别会显示什么吗?
>>> class C:
        def __getattr__(self, name):
                print(1)
                return super().__getattr__(name)
        def __getattribute__(self, name):
                print(2)
                return super().__getattribute__(name)
        def __setattr__(self, name, value):
                print(3)
                super().__setattr__(name, value)
        def __delattr__(self, name):
                print(4)
                super().__delattr__(name)

               
>>> c = C()
>>> c.x
复制代码

答:在不上机的情况下,我相信80%以上的鱼油很难猜到正确的答案T_T=+BPNjLlUT
qht]1
>>> c = C()
>>> c.x
2
1
Traceback (most recent call last):
  File "<pyshell#31>", line 1, in <module>
    c.x
  File "<pyshell#29>", line 4, in __getattr__
    return super().__getattr__(name)
AttributeError: 'super' object has no attribute '__getattr__'
复制代码

为什么会如此显示呢?我们来分析下:首先 c.x 会先调用 __getattribute__() 魔法方法,打印 2;然后调用 super().__getattribute__(),找不到属性名 x,因此会紧接着调用 __getattr__() ,于是打印 1;但是你猜到了开头没猜到结局……当你希望最后以 super().__getattr__() 终了的时候,Python 竟然告诉你 AttributeError,super 对象木有 __getattr__ !!A6pW4
}a>EISqDC
求证:O~U{a1
>>> dir(super)
['__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__']




为什么会报错呢?super为什么没有__getattr__??
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2018-8-20 19:34:58 | 显示全部楼层
因为基类(所有的类其实都是继承自object类,最基类)没有。
  1. >>> dir(object)
  2. ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
复制代码

喏,没有吧~
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2018-8-20 22:59:37 | 显示全部楼层
哦,本来就没有哦
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2018-8-20 23:00:40 | 显示全部楼层
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-4-19 11:07

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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