Dynamically adding @property in python

Posted by rz on Stack Overflow See other posts from Stack Overflow or by rz
Published on 2010-06-02T00:49:46Z Indexed on 2010/06/02 0:53 UTC
Read the original article Hit count: 215

Filed under:

I know that I can dynamically add an instance method to an object by doing something like:

import types
def my_method(self):
    # logic of method
# ...
# instance is some instance of some class
instance.my_method = types.MethodType(my_method, instance)

Later on I can call instance.my_method() and self will be bound correctly and everything works.

Now, my question: how to do the exact same thing to obtain the behavior that decorating the new method with @property would give?

I would guess something like:

instance.my_method = types.MethodType(my_method, instance)
instance.my_method = property(instance.my_method)

But, doing that instance.my_method returns a property object.

© Stack Overflow or respective owner

Related posts about python