Skip to content Skip to sidebar Skip to footer

Adding `__getattr__` Method To An Existing Object Instance

I would like this to work: import types def new_getattr(self, *args, **kwargs): return 2 class A: def __init__(self): pass a = A() a.__getattr__ = types.MethodTy

Solution 1:

You can not - __dunder__ names are resolved on the type, not per-instance. Custom __getattr__ will need to be defined directly on A.

See Special method lookup section of the datamodel documentation, specifically:

For custom classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary.

Note: if you only have a reference to an instance, not the class, it is still possible to monkeypatch the type by assigning a method onto the object returned by type(a). Be warned that this will affect all existing instances, not just the a instance.

Post a Comment for "Adding `__getattr__` Method To An Existing Object Instance"