How do I implement __getattribute__ without an infinite recursion error?

前端 未结 6 1376
天命终不由人
天命终不由人 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:38

    Are you sure you want to use __getattribute__? What are you actually trying to achieve?

    The easiest way to do what you ask is:

    class D(object):
        def __init__(self):
            self.test = 20
            self.test2 = 21
    
        test = 0
    

    or:

    class D(object):
        def __init__(self):
            self.test = 20
            self.test2 = 21
    
        @property
        def test(self):
            return 0
    

    Edit: Note that an instance of D would have different values of test in each case. In the first case d.test would be 20, in the second it would be 0. I'll leave it to you to work out why.

    Edit2: Greg pointed out that example 2 will fail because the property is read only and the __init__ method tried to set it to 20. A more complete example for that would be:

    class D(object):
        def __init__(self):
            self.test = 20
            self.test2 = 21
    
        _test = 0
    
        def get_test(self):
            return self._test
    
        def set_test(self, value):
            self._test = value
    
        test = property(get_test, set_test)
    

    Obviously, as a class this is almost entirely useless, but it gives you an idea to move on from.

提交回复
热议问题