仅在第一次调用变量时进行工作的 Pythonic 方式 [英] Pythonic way to only do work first time a variable is called

查看:26
本文介绍了仅在第一次调用变量时进行工作的 Pythonic 方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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?

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

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)

谢谢

推荐答案

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__,这就是它的工作原理

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__() 在对象上不存在属性时调用,即.第一次尝试访问 age.每次之后,age 都存在,所以 __getattr__ 不会被调用

__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

这篇关于仅在第一次调用变量时进行工作的 Pythonic 方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆