|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
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函数起了什么作用。
为什么会打印“被拦截了”
看帮助文档可知 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.
>>>
|
|