【发布时间】:2018-10-09 19:56:31
【问题描述】:
参考现有问题的第二个最佳答案:Difference between __getattr__ vs __getattribute__,其中包括某人建议的代码:
class Count(object):
def __init__(self, mymin, mymax):
self.mymin = mymin
self.mymax = mymax
self.current = None
def __getattr__(self, item):
self.__dict__[item] = 0
return 0
def __getattribute__(self, item):
if item.startswith('cur'):
raise AttributeError
return super(Count, self).__getattribute__(item)
obj1 = Count(1, 10)
print(obj1.mymin)
print(obj1.mymax)
print(obj1.current)
我的问题是:
当我运行代码时,它确实没有遇到无限递归深度(以超出最大递归深度结束)。为什么?而且,如果我将代码 super(Count, self).__getattribute__(item) 更改为 super(object, self).__getattribute__(item),它确实会陷入无限循环。为什么又来了?
请用详细的调用过程说明原因。
【问题讨论】:
-
不相关,但更新对象的状态 - 并最终创建新属性 - 在属性查找上是一个非常糟糕的主意(除非你只在受保护的属性中缓存一些值,但这里不是这种情况)
-
"当我运行代码时,它没有遇到无限递归" => 为什么会这样???
-
@brunodesthuilliers 我将“return super(Count, self).__getattribute__(item)”这一行更改为“return super(object, self).__getattribute__(item)”,然后就成功了。
-
你永远不应该写
super(object, self)。曾经。那永远不可能是正确的。 上面没有任何东西object.
标签: python