仅在第一次调用变量时才执行工作的 Pythonic 方式

发布于 2024-08-08 07:40:10 字数 352 浏览 2 评论 0原文

我的 Python 类有一些变量需要在第一次调用时进行计算。后续调用应该只返回预先计算的值。

我不想浪费时间做这项工作,除非用户确实需要它们。 那么有没有一种干净的 Pythonic 方式来实现这个用例呢?

我最初的想法是第一次使用 property() 调用函数,然后覆盖变量:

class myclass(object):
    def get_age(self):
        self.age = 21 # raise an AttributeError here
        return self.age

    age = property(get_age)

谢谢

my Python class has some variables that require work to calculate the first time they are called. Subsequent calls should just return the precomputed value.

I don't want to waste time doing this work unless they are actually needed by the user.
So is there a clean Pythonic way to implement this use case?

My initial thought was to use property() to call a function the first time and then override the variable:

class myclass(object):
    def get_age(self):
        self.age = 21 # raise an AttributeError here
        return self.age

    age = property(get_age)

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

十年不长 2024-08-15 07:40:10
class myclass(object):
    def __init__(self):
        self.__age=None
    @property
    def age(self):
        if self.__age is None:
            self.__age=21  #This can be a long computation
        return self.__age

Alex提到您可以使用__getattr__,这就是它的工作原理,

class myclass(object):
    def __getattr__(self, attr):
        if attr=="age":
            self.age=21   #This can be a long computation
        return super(myclass, self).__getattribute__(attr)

当对象上不存在该属性时,即调用__getattr__()。第一次尝试访问age时。此后每次,age 都存在,因此 __getattr__ 不会被调用

class myclass(object):
    def __init__(self):
        self.__age=None
    @property
    def age(self):
        if self.__age is None:
            self.__age=21  #This can be a long computation
        return self.__age

Alex mentioned you can use __getattr__, this is how it works

class myclass(object):
    def __getattr__(self, attr):
        if attr=="age":
            self.age=21   #This can be a long computation
        return super(myclass, self).__getattribute__(attr)

__getattr__() is invoked when the attribute doesn't exist on the object, ie. the first time you try to access age. Every time after, age exists so __getattr__ doesn't get called

痞味浪人 2024-08-15 07:40:10

如您所见,property 不会让您覆盖它。您需要使用稍微不同的方法,例如:

class myclass(object):

    @property
    def age(self):
      if not hasattr(self, '_age'):
        self._age = self._big_long_computation()
      return self._age

还有其他方法,例如 __getattr__ 或自定义描述符类,但这个更简单!-)

property, as you've seen, will not let you override it. You need to use a slightly different approach, such as:

class myclass(object):

    @property
    def age(self):
      if not hasattr(self, '_age'):
        self._age = self._big_long_computation()
      return self._age

There are other approaches, such as __getattr__ or a custom descriptor class, but this one is simpler!-)

酸甜透明夹心 2024-08-15 07:40:10

这里是来自 Python Cookbook 针对此问题:

class CachedAttribute(object):
    ''' Computes attribute value and caches it in the instance. '''
    def __init__(self, method, name=None):
        # record the unbound-method and the name
        self.method = method
        self.name = name or method.__name__
    def __get__(self, inst, cls):
        if inst is None:
            # instance attribute accessed on class, return self
            return self
        # compute, cache and return the instance's attribute value
        result = self.method(inst)
        setattr(inst, self.name, result)
        return result

Here is decorator from Python Cookbook for this problem:

class CachedAttribute(object):
    ''' Computes attribute value and caches it in the instance. '''
    def __init__(self, method, name=None):
        # record the unbound-method and the name
        self.method = method
        self.name = name or method.__name__
    def __get__(self, inst, cls):
        if inst is None:
            # instance attribute accessed on class, return self
            return self
        # compute, cache and return the instance's attribute value
        result = self.method(inst)
        setattr(inst, self.name, result)
        return result
情栀口红 2024-08-15 07:40:10

这个问题已经有11年历史了,python 3.8及以上版本现在带有 cached_property,它完美地满足了这个目的。该属性将仅计算一次,然后保存在内存中以供后续使用。

以下是在这种情况下如何使用它:

class myclass(object):
    @cached_property
    def age(self):
        return 21  #This can be a long computation

This question is already 11 years old, and python 3.8 and above now come with cached_property, which perfectly serves this purpose. The property will be computed only once, then kept in memory for subsequent use.

Here is how to use it in this case:

class myclass(object):
    @cached_property
    def age(self):
        return 21  #This can be a long computation
逆光下的微笑 2024-08-15 07:40:10

是的,您可以使用属性,尽管惰性评估通常也可以使用描述符来完成,请参见例如:

http://blog.pythonisito.com/2008/08/lazy-descriptors.html

Yes you can use properties, though lazy evaluation is also often accomplished using descriptors, see e.g:

http://blog.pythonisito.com/2008/08/lazy-descriptors.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文