【发布时间】:2017-01-08 17:24:20
【问题描述】:
我有以下代码。
class DobleTSim():
def __init__(self, bf, hw, tf, tw):
self.bf = bf
self.hw = hw
self.tf = tf
self.tw = tw
def m_in_maj(self):
print('foo')
return 2 * (self.bf * self.tf * (self.tf / 2 + self.hw / 2))
def m_est_maj(self):
return self.m_in_maj() / ((self.hw + 2 * self.tf) / 2)
A = DobleTSim(200, 500, 12, 12)
print(A.m_in_maj(), A.m_est_maj())
当我执行代码时,输出是:
foo
foo
1228800.0 4690.076335877862
如何避免两次执行“m_in_maj”方法?
-----编辑-----
另一个解决方案是使用 property 和 lru_cache 装饰器。使用这个有什么缺点吗?
import functools
class DobleTSim():
def __init__(self, bf, hw, tf, tw):
self.bf = bf
self.hw = hw
self.tf = tf
self.tw = tw
@property
@functools.lru_cache()
def m_in_maj(self):
print('foo')
self.a = 2 * (self.bf * self.tf * (self.tf / 2 + self.hw / 2))
return self.a
def m_est_maj(self):
return self.m_in_maj / ((self.hw + 2 * self.tf) / 2)
【问题讨论】:
-
m_in_maj()在m_est_maj()函数中被调用 -
不要在
m_est_maj中调用它 -
是的,但我需要这个值才能在 m_est_maj 上使用它。
-
print(A.m_est_maj())不适合你吗?