|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
各位大神:
我在看小甲鱼Python视频类和对象(XI)-属性访问相关魔法方法中讲解__getattribute__()魔法方法的例子时,例子如下:
class C:
def __init__(self, name, age):
self.name = name
self.__age = age
def __getattribute__(self, attrname):
print('拿来吧你')
return super().__getattribute__(attrname)
问题1:return super().__getattribute__(attrname)中的super()起的什么作用?
问题2:如果把return super().__getattribute__(attrname)中的super().进行删除,则代码变为如下:
class C:
def __init__(self, name, age):
self.name = name
self.__age = age
def __getattribute__(self, attrname):
print('拿来吧你')
return __getattribute__(attrname)
当执行c = C('小甲鱼', 18)时,为何显示4遍'拿来吧你'?
本帖最后由 lxping 于 2022-12-3 22:02 编辑
1、因为objects是类C的父类,且object中有__getattribute__(attrname)这个魔法方法,使用super().__getattribute__(attrname)可以避免:使用return self.__getattribute__(attrname),在使用self.name或者self._age进行属性访问的时候进入的无线递归循环。
2、删掉super(),实例化对象没有你说的情况呀,但是属性访问就会有问题
- class C:
- def __init__(self, name, age):
- self.name = name
- self.__age = age
- def __getattribute__(self, attrname):
- print('拿来吧你')
- return __getattribute__(attrname)
- c = C("小甲鱼", 18)
- c.name
- 拿来吧你
- Traceback (most recent call last):
- File "<pyshell#23>", line 1, in <module>
- c.name
- File "<pyshell#14>", line 7, in __getattribute__
- return __getattribute__(attrname)
- NameError: name '__getattribute__' is not defined
复制代码
|
|