Files
2026-09-23 21:27:55 +08:00

36 lines
779 B
Python

from functools import cached_property
class Person:
def __init__(self, height, bmi):
self.height = height
self.bmi = bmi
@cached_property
def weight(self):
print("====正在执行复杂计算====")
return self.height ** 2 * self.bmi
p = Person(1.75, 22)
# 第一次访问:执行函数,打印日志,保存结果
print(p.weight)
# 第二次访问:直接读缓存!不会打印日志,不重新计算
print(p.weight)
print(p.weight)
class Person2:
def __init__(self, height, bmi):
self.height = height
self.bmi = bmi
@property
def weight(self):
print("====每次都重新计算====")
return self.height ** 2 * self.bmi
p2 = Person2(1.75,22)
print(p2.weight)
print(p2.weight)