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 following (which should also illustrate what I’m trying to do) but I get a recursion error:
class D(object): def __init__(self): self.test=20 self.test2=21 def __getattribute__(self,name): if name=='test': return 0. else: return self.__dict__[name] >>> print D().test 0.0 >>> print D().test2 ... RuntimeError: maximum recursion depth exceeded in cmp
You get a recursion error because your attempt to access the
self.__dict__attribute inside__getattribute__invokes your__getattribute__again. If you useobject‘s__getattribute__instead, it works:This works because
object(in this example) is the base class. By calling the base version of__getattribute__you avoid the recursive hell you were in before.Ipython output with code in foo.py:
Update:
There’s something in the section titled More attribute access for new-style classes in the current documentation, where they recommend doing exactly this to avoid the infinite recursion.