递归的原因是什么?

问题描述 投票:-1回答:1

Difference between __getattr__ vs __getattribute__上有一些很好的例子来__getattr___getattribute__

__getattribute__为什么叫了19次 - 在代码之后?好的 - 这是一次递归......但为什么呢?

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):
        print("__getattribute__: ", item)          # only this line is new!!!!
        if item.startswith('cur'):
            raise AttributeError
        return object.__getattribute__(self,item)
        # or you can use ---return super().__getattribute__(item)
        # note this class subclass object

obj1 = Count(1,10)
print(obj1.mymin)
print(obj1.mymax)
print(obj1.current)
print("end")

输出:

__getattribute__:  mymin
1
__getattribute__:  mymax
10
__getattribute__:  current
__getattribute__:  __dict__
0
end
__getattribute__:  __class__
__getattribute__:  __class__
__getattribute__:  __class__
__getattribute__:  __class__
__getattribute__:  __class__
__getattribute__:  __class__
__getattribute__:  __class__
__getattribute__:  __class__
__getattribute__:  __class__
__getattribute__:  __class__
__getattribute__:  __class__
__getattribute__:  __class__
__getattribute__:  __class__
__getattribute__:  __class__
__getattribute__:  __class__
__getattribute__:  __class__
__getattribute__:  __class__
__getattribute__:  __class__
__getattribute__:  __class__
python python-3.x recursion getattribute
1个回答
0
投票

使用Python 3.7,我可以重现您的问题的唯一方法是在代码中放置断点和调试。

因此,对Count.__getattribute__的多次调用很可能是由尝试访问类属性的其他东西(在我的情况下:调试器)引起的。

对于记录,这是我以正常方式运行代码时的跟踪:

__getattribute__:  mymin
1
__getattribute__:  mymax
10
__getattribute__:  current
__getattribute__:  __dict__
0
end

请注意,即使访问obj1.current,也不会显示异常跟踪。这是我无法解释的具体行为。

© www.soinside.com 2019 - 2024. All rights reserved.