Dynamically Set An Instance Property / Memoized Attribute In Python?
I have an existing example class in Python 2.7x class Example(object): a = None b = None c = None and an existing instance anInstance = Example() anInstance.a = 100 an
Solution 1:
You can alter python classes after the fact:
@propertydefc(self):
if self._c isNone:
self._c = DO EXPENSIVE STUFF HERE
return self._c
Example.c = c
Example._c = NoneNow you've added a property c to your class, as well as add a _c attribute.
You may need to override any existing methods on the class that assume they can assign to self.c, of course.
The process of dynamically adding or replacing attributes of objects is often referred to as Monkey Patching.
Post a Comment for "Dynamically Set An Instance Property / Memoized Attribute In Python?"