鱼C论坛

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

[已解决]为什么

[复制链接]
发表于 2023-8-29 16:46:21 | 显示全部楼层 |阅读模式

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

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

x
class C:
    def __init__(self,name,age):
        self.name = name
        self.__age = age
    def __getattribute__(self,attrname):
        print("被拦截了")
        return super().__getattribute__(attrname)
定义了一个类C
然后
c = C("哈哈哈",18)
getattr(c,"name")
为什么会输出
被拦截了
“哈哈哈”
搞不懂这个重写的__getattribute__魔法方法对python自带的getattr函数起了什么作用。
为什么会打印“被拦截了”
最佳答案
2023-8-29 17:54:40
看帮助文档可知 getattr(x, y) 相当于 x.y

而 x.y 是会去调用 __getattribute__ 的,因为你重写了 __getattribute__ ,所以会打印“被拦截了”

>>> help(getattr)
Help on built-in function getattr in module builtins:

getattr(...)
    getattr(object, name[, default]) -> value

    Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
    When a default argument is given, it is returned when the attribute doesn't
    exist; without it, an exception is raised in that case.

>>>

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2023-8-29 16:46:46 | 显示全部楼层
在这段代码中,类C重写了 __getattribute__ 魔法方法。 __getattribute__ 方法在访问对象的属性时被调用。

当我们调用 getattr(c, "name") 时, getattr 函数会尝试获取对象 c 的属性 name 。由于类C重写了 __getattribute__ 方法,所以在获取属性之前,会先执行 print("被拦截了") 语句。

super().__getattribute__(attrname) 调用了父类的 __getattribute__ 方法,实际上是获取了对象的属性值。因此,最终输出的结果是 "哈哈哈" 。

重写 __getattribute__ 方法的作用是在获取对象属性时进行拦截和处理。在这个例子中,打印了一条信息表示属性被拦截了,然后继续获取属性的值并返回。这样可以在属性访问时添加额外的逻辑或者对属性进行保护。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2023-8-29 17:54:40 | 显示全部楼层    本楼为最佳答案   
看帮助文档可知 getattr(x, y) 相当于 x.y

而 x.y 是会去调用 __getattribute__ 的,因为你重写了 __getattribute__ ,所以会打印“被拦截了”

>>> help(getattr)
Help on built-in function getattr in module builtins:

getattr(...)
    getattr(object, name[, default]) -> value

    Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
    When a default argument is given, it is returned when the attribute doesn't
    exist; without it, an exception is raised in that case.

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

使用道具 举报

发表于 2023-8-29 17:57:08 | 显示全部楼层
你在getattr里面加了一个print,就这么简单
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-6-9 10:43

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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