Python __getattribute__回退到__getattr__

时间:2019-02-04 15:45:09

标签: python

我遇到一种情况,其中 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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您需要咨询python Data model

getattribute的摘录:

  

无条件调用以实现类实例的属性访问。如果该类还定义了 getattr (),则除非 getattribute ()显式调用它或引发AttributeError,否则不会调用后者。

我在您的代码中看到了

if item.startswith('cur'):
    print("this raised an error")
    raise AttributeError

所以我认为您是故意这样做的