python - 用于路径传播的链式运算符重载

标签 python operator-overloading

我想用 python 实现一个简单的光传播模型。规则是,如果我链接三个元素 m0 -> m1-> m2 我将得到的系统是:

  • tau = tau0 * tau1 * tau2
  • B = B2 + B1*tau2 + B0*tau2*tau1

(tau 为传输,B 为背景)。

我想实现重载 __gt__ 运算符,以便我可以声明:

m0 = Mirror(0.9, 10)
m1 = Mirror(0.8, 11)
m2 = Mirror(0.7, 12)
x = m0 > m1 > m2

到目前为止我写了这个:

class OpticalElement:
    def __init__(self, trans, background):
        self.trans = trans
        self.background = background

class Mirror(OpticalElement):       
    def __gt__(self, other):
        if isinstance(other, Mirror):
            tau = self.trans * other.trans
            bkg = other.background + other.trans * self.background
            return Mirror(tau, bkg)
        else:
            return NotImplemented

但是这段代码似乎只能获取最右边元素的传输和背景:

x = m0 > m1 > m2
x.trans

返回 0.56,而我期望 0.504。 背景行为相同,我得到 19.7 而不是 25.3(忽略第一个元素)。

你们知道如何使用运算符重载实现多个链式元素吗?(添加括号是可行的,但我想要更清晰的代码)。

谢谢!

安德鲁

最佳答案

m0 > m1 > m2 相当于 (m0 > m1) 和 (m1 > m2)

由于 m0 > m1 将被视为 Trueand 将测试 m1 > m2 并返回其值,这是您得到的 0.56。

您可以使用乘法运算符,它将按预期工作:

class OpticalElement:
    def __init__(self, trans, background):
        self.trans = trans
        self.background = background

class Mirror(OpticalElement):       
    def __mul__(self, other):
        if isinstance(other, Mirror):
            tau = self.trans * other.trans
            bkg = other.background + other.trans * self.background
            return Mirror(tau, bkg)
        else:
            return NotImplemented

m0 = Mirror(0.9, 10)
m1 = Mirror(0.8, 11)
m2 = Mirror(0.7, 12)
x = m0 *m1 * m2
print(x.trans)
#0.504

关于python - 用于路径传播的链式运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49296230/

相关文章:

python - map(function, sequence) 其中函数返回两个值

c++ - 了解运算符查找;哪个编译器是正确的?

C++赋值重载自赋值问题

c++ - 重载操作符 << 时出错

c++ - 重载运算符上的 bad_lexical_cast 异常 ">>"

c++ - unique_ptr < 0 或者小于运算符做什么?

python - Airflow 从与执行文件相同的指定路径中的文件导入时出现问题

python - 加载 JSON 并获取某些数据 (Python)

python - 在 Python 和 Windows 7 中使用 "findstr"循环遍历 stdout 命令行内容

ruby watirrecorder 的 Python 替代品?