Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-什么是惰性属性?_Python_Python 2.7_Properties_Webapp2 - Fatal编程技术网

Python-什么是惰性属性?

Python-什么是惰性属性?,python,python-2.7,properties,webapp2,Python,Python 2.7,Properties,Webapp2,在线浏览webapp2文档时,我找到了有关decoratorwebapp2.cached_属性的信息(可在中找到) 文件中说: 将函数转换为惰性属性的装饰器 我的问题是: 什么是懒惰的财产 谢谢 它是一个属性修饰符,在第一次调用后会被忽略。它允许您自动缓存计算值 是且始终被调用,即使在相同名称的实例上存在属性也是如此 另一方面,@cached_属性装饰器只有一个\uuuu get\uuu方法,这意味着如果已经存在同名的属性,则不会调用它。它通过在第一次调用时在实例上设置一个同名的属性来利用这一点

在线浏览webapp2文档时,我找到了有关decorator
webapp2.cached_属性的信息(可在中找到)

文件中说:

将函数转换为惰性属性的装饰器

我的问题是:

  • 什么是懒惰的财产

  • 谢谢

    它是一个
    属性
    修饰符,在第一次调用后会被忽略。它允许您自动缓存计算值

    是且始终被调用,即使在相同名称的实例上存在属性也是如此

    另一方面,
    @cached_属性
    装饰器只有一个
    \uuuu get\uuu
    方法,这意味着如果已经存在同名的属性,则不会调用它。它通过在第一次调用时在实例上设置一个同名的属性来利用这一点

    在名为
    foo
    的实例上,给定一个
    @cached_属性
    -修饰的
    bar
    方法,会发生以下情况:

    • Python解析
      foo.bar
      。在实例上找不到
      属性

    • Python在类上找到
      描述符,并在该类上调用
      \uuuu get\uuu

    • cached\u属性
      获取
      方法调用修饰的
      方法

    • bar
      方法计算某些内容,并返回字符串
      'spam'

    • cached\u属性
      \uuuu get\uuu
      方法获取返回值,并在实例上设置一个新属性
      bar
      <代码>foo.bar=‘垃圾邮件’

  • cached\u属性
    获取
    方法返回
    'spam'
    返回值

  • 如果再次请求
    foo.bar
    ,Python会在实例上找到
    bar
    属性,并从此处开始使用该属性

  • 另见:


    请注意,从Python 3.8开始,标准库有一个类似的对象。它的实现更加健壮,它可以防止在不同名称下意外重复使用,如果在没有
    \uuu dict\uuuu
    属性的对象上使用,或者在该对象不支持项分配的情况下,会生成更好的错误消息,而且也是线程安全的。

    A
    functools.cached_属性
    是在Python-3.8中添加的。@martineau:是的,谢谢你告诉我这个问题的答案。我在答案中添加了一个简短的介绍。
    # implementation detail: this property is implemented as non-data
    # descriptor.  non-data descriptors are only invoked if there is
    # no entry with the same name in the instance's __dict__.
    # this allows us to completely get rid of the access function call
    # overhead.  If one choses to invoke __get__ by hand the property
    # will still work as expected because the lookup logic is replicated
    # in __get__ for manual invocation.