Friday 15 June 2012

monkeypatching - dynamically set an instance property / memoized attribute in python? -


The current example class in my Python 2.7x

  class example (object): A = None B = Any C = None   

And an existing example

  An example = example () anInstance.a = 100 anInstance. B = 200 one ins. C = 300   

I am reconstituting / cleaning some code, and now it is known that anInstance.c is an expensive operation Which is rarely used. / P>

In an ideal world I will do this:

  class example (object): _c = none @property def c (self): if self._c is none: self ._c = Spend heavy duty here yourself C   

The problem is that I can not change the class example right now. [Therefore, Quickfix will have to set it as a function, and I will replace every obj.c to obj.c () ]

I know that there is no way, unless I can change the object, I can dynamically allocate a property / memoisonation. Is this understanding correct? I am hoping to be disappointed here, I just want confirmation.

You can change python classes Fact:

  @property Def c (self): If self._c is not any: self._c = Heavy duty here to spend yourself here. C example example = c example._c = none   

Now you've added an asset to your class c , as well as _c attribute.

You may need to override any existing methods in the class, which they can assign to self.c .

The process of dynamically adding or changing the properties of objects is often referred to as.

No comments:

Post a Comment