如何在 class 中正确设置多个依赖属性?

How to properly set multiple dependent attributes in a class?

我正在寻找一种在 class 中设置多个依赖属性的方法。也许这个例子进一步说明了我正在尝试做的事情。目前我正在用多个嵌套的 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))

正确的做法是什么?

根据您的逻辑,必须要求至少设置参数 fomega 之一,否则应该失败。您可以使用以下语句对此进行断言:

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
    ...