我有一個閉包,它應該保存計算量大的函式的回傳值以供重用。但是,當我運行完全相同的代碼行 ( _ = cached_readonly_property(lambda: "b")) 時,我會根據變數是類變數 ( b) 還是實體變數 ( c) 獲得不同的回傳值。為什么會這樣?有沒有辦法讓return "a" 和returnself.a一樣?self.b"b"
def cached_readonly_property(return_callable: Callable):
cached_value = None
@property
def prop(self):
nonlocal cached_value
if cached_value is None:
cached_value = return_callable()
return cached_value
return prop
class A:
b = cached_readonly_property(lambda: "b")
def __init__(self) -> None:
self.a = cached_readonly_property(lambda: "a")
print()
a = A()
print(a.a)
print(a.a)
print(a.b)
print(a.b)
# Outputs:
# <property object at 0x10d2106d0>
# <property object at 0x10d2106d0>
# b
# b
uj5u.com熱心網友回復:
屬性描述符僅支持類變數的系結行為。
Python 運行時在屬性查找期間將類變數轉換為以下內容。
type(a).__dict__['b'].__get__(b, type(b))
對于a屬性,您需要直接呼叫以讀取其值。
print(a.a.__get__(a))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/520870.html
上一篇:無法在物件中添加屬性
下一篇:如何獲得多個物件中整數的總和?
