python - 在 Python 中创建 LazilyEvaluatedConstantProperty 类

标签 python attributes properties

我想在 Python 中做一些小事情,类似于内置的 property,但我不知道该怎么做。

我将这个类称为LazilyEvaluatedConstantProperty。它适用于仅计算一次且不更改的属性,但为了性能,应延迟创建它们而不是在创建对象时创建。

用法如下:

class MyObject(object):

    # ... Regular definitions here

    def _get_personality(self):
        # Time consuming process that creates a personality for this object.
        print('Calculating personality...')
        time.sleep(5)
        return 'Nice person'

    personality = LazilyEvaluatedConstantProperty(_get_personality)

您可以看到其用法与property类似,只不过只有一个getter,没有setter或deleter。

目的是在第一次访问my_object.personality时,将调用_get_personality方法,然后将结果缓存并_get_personality 永远不会再为此对象调用。

我在实现这个过程中遇到了什么问题?我想做一些有点棘手的事情来提高性能:我希望在第一次访问和 _get_personality 调用之后,personality 将成为对象的数据属性,因此查找将后续通话速度更快。但我不知道这怎么可能,因为我没有对该对象的引用。

有人有想法吗?

最佳答案

我实现了它:

class CachedProperty(object):
    '''
    A property that is calculated (a) lazily and (b) only once for an object.

    Usage:

        class MyObject(object):

            # ... Regular definitions here

            def _get_personality(self):
                print('Calculating personality...')
                time.sleep(5) # Time consuming process that creates personality
                return 'Nice person'

            personality = CachedProperty(_get_personality)

    '''
    def __init__(self, getter, name=None):
        '''
        Construct the cached property.

        You may optionally pass in the name that this property has in the
        class; This will save a bit of processing later.
        '''
        self.getter = getter
        self.our_name = name


    def __get__(self, obj, our_type=None):

        if obj is None:
            # We're being accessed from the class itself, not from an object
            return self

        value = self.getter(obj)

        if not self.our_name:
            if not our_type:
                our_type = type(obj)
            (self.our_name,) = (key for (key, value) in 
                                vars(our_type).iteritems()
                                if value is self)

        setattr(obj, self.our_name, value)

        return value

对于 future ,维护的实现可能可以在这里找到:

https://github.com/cool-RR/GarlicSim/blob/master/garlicsim/garlicsim/general_misc/caching/cached_property.py

关于python - 在 Python 中创建 LazilyEvaluatedConstantProperty 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3265221/

相关文章:

python - Pip 卡在 "collecting numpy"

jsp - JSP 标记的 Outcomment 属性

java - 创建 IO 流对象

properties - 如何从 SOAP UI 中的外部文件加载属性?

python - 从 stdin python 读取

python - 使用生成器生成排列

forms - 如何在 Symfony 表单类型中添加 VueJS v-model 属性

java - 修改java中的文件

python - Dask Dataframe 分布式进程 ID 访问被拒绝

python - 为什么我的 python 子类无法识别父类(super class)的属性?