python - 为什么调用超类`__getattribute__`会导致无限递归?
问题描述
显然,以下将导致无限循环:
class Klaus:
def __getattribute__(self, key):
return getattr(type(self), key)
但是,我不明白为什么调用超类__getattribute__
会:
class Parent:
def __init__(self):
print("begin __init__")
self._x = 3
print("end __init__")
def __getattribute__(self, attr_name):
superk = super(type(self), self)
boohl = superk.__getattribute__ == self.__getattribute__
print("with age comes wisdom", boohl)
return superk.__getattribute__(attr_name)
class Child(Parent):
def __getattribute__(self, attr_name):
superk = super(type(self), self)
boohl = superk.__getattribute__ == self.__getattribute__
print("this booger is green!", boohl)
return super(type(self), self).__getattribute__(attr_name)
obj = Child()
print("lambda")
print(obj._x)
print("anonymous")
解决方案
因为永远type(self)
是孩子。即使您在 Parent 的方法中,仍然是 Child 的实例。self
这就是为什么当您使用长格式时,super
您必须始终显式使用当前类,而不是 this。当然,在 Python 3 中,super()
无论如何您都可以不带任何参数使用。
推荐阅读
- datatable - 如果表为空,则 JQuery 响应式数据表不起作用
- tabulator - 我错过了如何正确添加按钮吗?
- mysql - SQL 为每个不同的设备 ID 选择 200 个最近的时间戳
- php - 如何通过过滤MySql上的多个列来限制多个数字?
- c# - .net 核心控制台应用程序使用基本身份验证调用 PHP REST API
- python - 在 if 语句中添加地址
- r - R Shiny 在侧边栏中布置 2x2 表格,以便数字输入可见
- javascript - 我需要我的 ReactJS 应用程序在没有服务器的情况下离线工作
- perl - 将哈希传递给子例程而不更改其输入
- javascript - 数据列表和结果重定向有问题