How do I implement __getattribute__ without an infinite recursion error?

前端 未结 6 1358
天命终不由人
天命终不由人 2020-11-27 10:18

I want to override access to one variable in a class, but return all others normally. How do I accomplish this with __getattribute__?

I tried the follo

6条回答
  •  渐次进展
    2020-11-27 10:44

    Here is a more reliable version:

    class D(object):
        def __init__(self):
            self.test = 20
            self.test2 = 21
        def __getattribute__(self, name):
            if name == 'test':
                return 0.
            else:
                return super(D, self).__getattribute__(name)
    

    It calls __getattribute__ method from parent class, eventually falling back to object.__getattribute__ method if other ancestors don't override it.

提交回复
热议问题