python:是否自动缓存属性字段? [英] python: are property fields being cached automatically?

查看:32
本文介绍了python:是否自动缓存属性字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是解释器运行的以下两段代码是否相同:

My question is are the following two pieces of code run the same by the interpreter:

class A(object):
  def __init__(self):
     self.__x = None

  @property
  def x(self):
     if not self.__x:
        self.__x = ... #some complicated action
     return self.__x

还有更简单的:

class A(object):
  @property
  def x(self):
      return ... #some complicated action

即,解释器是否足够智能以缓存属性 x?

I.e., is the interpreter smart enough to cache the property x?

我的假设是 x 不会改变 - 找到它很难,但是一旦找到它就没有理由再次找到它.

My assumption is that x does not change - finding it is hard, but once you find it once there is no reason to find it again.

推荐答案

不,每次访问属性时都会调用 getter.

No, the getter will be called every time you access the property.

这篇关于python:是否自动缓存属性字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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