我试图多次使用类方法的结果,而不进行获得结果所需的繁重计算。
我看到以下选项。你认为哪些是正确的,或者更像 Pythonic?
每一种的优点和缺点是什么?
class Test:
def __init__(self, *args):
# do stuff
@property
def new_method(self):
try:
return self._new_property
except AttributeError:
# do some heavy calculations
return self._new_property
Run Code Online (Sandbox Code Playgroud)
from functools import lru_cache
class Test:
def __init__(self, *args):
# do stuff
@property
@lru_cache()
def new_method(self):
# do some heavy calculations
return self._new_property
Run Code Online (Sandbox Code Playgroud)
from django.utils.functional import cached_property
class Test:
def __init__(self, *args):
# do stuff
@cached_property
def new_method(self):
# do some heavy calculations
return self._new_property
Run Code Online (Sandbox Code Playgroud) 我需要使用numpy处理多个条件。
我正在尝试这段似乎可行的代码。
我的问题是:还有另一种方法可以完成相同的工作?
Mur=np.array([200,246,372])*pq.kN*pq.m
Mumax=np.array([1400,600,700])*pq.kN*pq.m
Mu=np.array([100,500,2000])*pq.kN*pq.m
Acreq=np.where(Mu<Mur,0,"zero")
Acreq=np.where(((Mur<Mu)&(Mu<Mumax)),45,Acreq)
Acreq=np.where(Mu>Mumax,60,Acreq)
Print(Acreq)
['0' '45' '60']
Run Code Online (Sandbox Code Playgroud)