python中and和or的惰性求值特点_Python中的惰性评估
一個名為python pattern和Wikipedia的github存儲庫告訴我們什么是惰性評估。
將expr的評估延遲到需要其值為止,并避免重復評估。
python3中的cached_property不是一個完整的延遲評估,因為它不能避免重復評估。
惰性評估的一個更經典的示例是cached_property:
import functools
class cached_property(object):
def __init__(self, function):
self.function = function
functools.update_wrapper(self, function)
def __get__(self, obj, type_):
if obj is None:
return self
val = self.function(obj)
obj.__dict__[self.function.__name__] = val
return val
cached_property(也稱為lazy_property)是一個裝飾器,可將功能轉換為惰性評估屬性。 首次訪問屬性時,將調用func以獲得結果,然后在下次訪問該屬性時使用該值。
例如:
class LogHandler:
def __init__(self, file_path):
self.file_path = file_path
@cached_property
def load_log_file(self):
with open(self.file_path) as f:
# the file is to big that I have to cost 2s to read all file
return f.read()
log_handler = LogHandler('./sys.log')
# only the first time call will cost 2s.
print(log_handler.load_log_file)
# return value is cached to the log_handler obj.
print(log_handler.load_log_file)
要使用適當的單詞,像range這樣的python生成器對象更像是通過call_by_need模式設計的,而不是惰性求值的
總結
以上是生活随笔為你收集整理的python中and和or的惰性求值特点_Python中的惰性评估的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【ES11(2020)】Promise
- 下一篇: centos运行python程序_Cen