I want to override access to one variable in a class, but return all others normally. How do I accomplish this with
>>> print D().test
>>> print D().test2
RuntimeError: maximum recursion depth exceeded in cmp
You get a recursion error because you call the same function, your
__getattribute__. If you use
__getattribute__ instead, it works:
class D(object): def __init__(self): self.test=20 self.test2=21 def __getattribute__(self,name): if name=='test': return 0. else: return object.__getattribute__(self, name)
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:
In : from foo import * In : d = D() In : d.test Out: 0.0 In : d.test2 Out: 21
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.