语法错误:无法分配给操作员

时间:2018-02-15 14:34:00

标签: python python-2.7 oop syntax-error

 def addOp(self):
        i = math.sqrt(-1) 
        addAnswer = (a + b*i) + (c + d*i) = (a + c) + (b + d)*i
        return addAnswer

当我运行我的代码时,它在'addAnswer'行上给我一个错误... 我已经尝试在需要时输入*并调整括号,但没有帮助。同样适用于以下代码

def mutliplicationOp(self):
        multiAnswer =  (a + b*i) * (c + d*i) = (a*c - b*d) + (b*c + a*d)*i
        return multiAnswer

2 个答案:

答案 0 :(得分:0)

def addOp(self):
        i = math.sqrt(-1)  # This will create a math domain error though...
        addAnswer = (a + b*i) + (c + d*i) = (a + c) + (b + d)*i
        return addAnswer

为什么这有两个任务? (a + b*i) + (c + d*i)(a + c) + (b + d)*i 等效。你只需要一个。第二段代码也是如此。只是做

def addOp(self):
        i = (-1)**0.5
        addAnswer = (a + c) + (b + d)*i
        return addAnswer

甚至更好

def addOp(self):
        return (a + c) + (b + d)*1j

并且类似于乘法部分。或者,使用内置的complex类型:

def addOp(self):
    return complex(a, b) + complex(c, d)

答案 1 :(得分:0)

这是你想要做的吗?

def function(c_a, c_b, operation):
    return {'+': c_a.__add__(c_b), 
            '*': c_a.__mul__(c_b), 
            '-': c_a.__sub__(c_b), 
            '/': c_a.__truediv__(c_b)
            }.get(operation, 'Operation "{}" not supported!'.format(operation))

示例运行:

print(function(complex(2, 2), complex(2, 2), '+'))  # -> (4+4j)
print(function(complex(2, 2), complex(2, 2), '-'))  # -> 0j
print(function(complex(2, 2), complex(2, 2), '*'))  # -> 8j
print(function(complex(2, 2), complex(2, 2), '/'))  # -> (1+0j)
print(function(complex(2, 2), complex(2, 2), '%'))  # -> Operation "%" not supported!