dynamically set an instance property / memoized attribute in python?

荒凉一梦 提交于 2020-01-06 07:14:02

问题


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
anInstance.b = 200
anInstance.c = 300

I've been refactoring/cleaning some code, and it's now known that anInstance.c is an expensive operation that is rarely used.

in a perfect world I would just do this :

class Example(object):
    _c = None
    @property
    def c(self):
        if self._c is not None:
           self._c = DO EXPENSIVE STUFF HERE
        return self._c

The problem is that I can't change class Example right now. [ So the quickfix would be to set it as a function, and change every obj.c to obj.c() ]

A far as I know there isn't any way that I can dynamically assign a property / memoization unless I alter the object. Is that understanding correct ? I'm expecting to be disappointed here, I just want the confirmation.


回答1:


You can alter python classes after the fact:

@property
def c(self):
    if self._c is None:
        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.

The process of dynamically adding or replacing attributes of objects is often referred to as Monkey Patching.



来源:https://stackoverflow.com/questions/17245201/dynamically-set-an-instance-property-memoized-attribute-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!