gpt4 book ai didi

python - 什么是惰性属性(property)?

转载 作者:太空狗 更新时间:2023-10-29 22:22:28 24 4
gpt4 key购买 nike

在网上浏览webapp2文档时,我找到了装饰器的信息:webapp2.cached_property

在文档中,它说:

A decorator that converts a function into a lazy property.

我的问题是:

什么是惰性属性?

最佳答案

它是一个 property 装饰器,在第一次调用后就会让开。它允许您自动缓存计算值。

standard library @property decoratordata descriptor object并且总是被调用,即使实例上有一个同名的属性也是如此。

另一方面,@cached_property 装饰器只有有一个__get__ 方法,这意味着如果有已存在同名属性。它通过在第一次调用时在实例上设置具有相同名称的属性来利用这一点。

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

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

  • Python 在类中找到 bar 描述符,并对其调用 __get__

  • cached_property __get__ 方法调用修饰的 bar 方法。

  • bar 方法计算一些东西,并返回字符串 'spam'

  • cached_property __get__ 方法获取返回值并在实例上设置一个新属性 barfoo.bar = '垃圾邮件'

  • cached_property __get__ 方法返回'spam' 返回值。

  • 如果您再次请求 foo.bar,Python 会在实例上找到 bar 属性,并从现在开始使用它。

另见 source code for the original Werkzeug implementation :

# 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.

请注意,从 Python 3.8 开始,标准库有一个类似的对象,@functools.cached_property() .它的实现更加健壮,它可以防止以不同的名称意外重用,如果在没有 __dict__ 属性的对象上使用或者在该对象不支持的地方使用,会产生更好的错误消息项目分配,也是线程安全的。

关于python - 什么是惰性属性(property)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24704147/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com