我正在寻找一种在一个类中设置多个依赖属性的方法。也许这个例子进一步说明了我想要做的事情。目前,我正在用多个嵌套的try语句来解决这个问题。这似乎不是正确的方式。
r"""
Example on sine-wave, where: a * sin(2 * pi * f * t + phi) = a * sin(omega * t + phi)
"""
import numpy as np
class SineWave:
def __init__(self, a: float = 1., phi: float = 0., f: float = None, omega: float = None):
self.a = a
self.f = f
self.phi = phi
self.omega = omega
self.post_init()
def post_init(self) -> None:
try:
self.f = self.omega / (2 * np.pi)
except TypeError:
self.omega = 2 * np.pi * self.f
def __call__(self, t: float) -> float:
return self.a * np.sin(self.omega * t + self.phi)
if __name__ == '__main__':
sin = SineWave(f=1)
print(sin(np.pi))这样做的正确方法是什么?
发布于 2021-09-15 08:20:46
根据您的逻辑,必须至少设置参数f和omega中的一个,否则将会失败。您可以使用以下语句来断言这一点:
def __init__(self, a: float = 1., phi: float = 0., f: float = None, omega: float = None):
if all(arg is None for arg in [f, omega]): # This is handy if you have multiple variables. But this could also be simply <if f is None and omega is None:>
raise ValueError("Required arguments are null")
...在检查之后,代码的下一部分的设计就很简单了,因为我们知道至少设置了其中的一个:
def __init__(...):
...
self.f = f if f is not None else omega / (2 * np.pi)
self.omega = omega if omega is not None else 2 * np.pi * f
...https://stackoverflow.com/questions/69189139
复制相似问题