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 = None
Now 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.
Baca Juga
- How To Dynamically Set An Object's Method At Runtime (when The Object Is An Instance Of A Gym Environment)?
- Should A Plugin Adding New Instance-methods Monkey-patch Or Subclass/mixin And Replace The Parent?
- Why The Model Is Training On Only 1875 Training Set Images If There Are 60000 Images In The Mnist Dataset?
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?"