Python __getattribute__回退到__getattr __

问题描述 投票:0回答:2

我有一种情况,其中getattribute退回到getattr,然后再次调用getattribute

如何重新调用当前getattribute?我很困惑。

class Count(object):

    def __init__(self,mymin,mymax):
        self.mymin=mymin
        self.mymax=mymax
        self.current=None

    def __getattr__(self, item):
            print("akhjhd")
            self.__dict__[item]=0
            return 0

    def __getattribute__(self, item):
        print("this is called first")
        if item.startswith('cur'):
            print("this raised an error")
            raise AttributeError
        print("This will execute as well")
        return object.__getattribute__(self,item)


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

控制台输出:

this is called first
This will execute as well
1
this is called first
This will execute as well
10
this is called first
this raised an error
akhjhd
this is called first
This will execute as well
0
python
2个回答
3
投票
  • [getattr之所以被调用是因为getattribute引发了AttributeError
  • [self.__dict__调用对getattribute的“第二个”调用>
  • 清除代码并添加print(item)使其更清晰:

class Count(object):
    def __init__(self):
        self.current = None

    def __getattr__(self, item):
        print("in getattr")
        self.__dict__[item] = 0
        return 0

    def __getattribute__(self, item):
        print(item)
        print("in __getattribute__ 1")
        if item.startswith('cur'):
            print("starts with 'cur'")
            raise AttributeError
        print("in __getattribute__ 2")
        return object.__getattribute__(self, item)


obj1 = Count()
print(obj1.current)

输出

current
in __getattribute__ 1
starts with 'cur'
in getattr
__dict__
in __getattribute__ 1
in __getattribute__ 2
0

0
投票

您需要咨询python Data model

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