鱼C论坛

 找回密码
 立即注册
查看: 4202|回复: 2

[已解决]类和对象(XI)-属性访问相关魔法方法中关于__getattribute__()魔法方法例子的困惑

[复制链接]
发表于 2022-12-3 20:11:00 | 显示全部楼层    本楼为最佳答案   
本帖最后由 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(),实例化对象没有你说的情况呀,但是属性访问就会有问题
  1. class C:
  2.     def __init__(self, name, age):
  3.         self.name = name
  4.         self.__age = age
  5.     def __getattribute__(self, attrname):
  6.         print('拿来吧你')
  7.         return __getattribute__(attrname)

  8. c = C("小甲鱼", 18)
  9. c.name
  10. 拿来吧你
  11. Traceback (most recent call last):
  12.   File "<pyshell#23>", line 1, in <module>
  13.     c.name
  14.   File "<pyshell#14>", line 7, in __getattribute__
  15.     return __getattribute__(attrname)
  16. NameError: name '__getattribute__' is not defined
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-11-4 08:24

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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