我正在做一个通用的重载运算符函数,它接受运算符+, - ,,/和* 。运算符以变量“op”形式出现。我的问题是将零除。第二个elif语句是我试图这样做的地方,但它并不完全正确。我想要涵盖的是两件事:如果self.list[L][0] == operand.list[R][0]
允许条件成立,其次如果右侧操作数在除法时不等于零(即op == '/'
和{{1 }})。如果它是假的,那么它只是转到else语句。
operand.list[R][1] != 0
答案 0 :(得分:1)
您可能需要将所有or
子句括在括号中。
由于and
的优先级高于or
,因此您的子句:
(self.list[L][0] == operand.list[R][0]) and op == '*' or op == '**' or op == '+' or op == '-' or (op == '/' and operand.list[R][1] != 0)
评估为
((self.list[L][0] == operand.list[R][0]) and op == '*') or op == '**' or op == '+' or op == '-' or (op == '/' and operand.list[R][1] != 0)
因此将其更改为
(self.list[L][0] == operand.list[R][0]) and (op == '*' or op == '**' or op == '+' or op == '-' or (op == '/' and operand.list[R][1] != 0))
应该做的伎俩。或者,如果您确定op
只能是您提到的那个之一:
(self.list[L][0] == operand.list[R][0]) and (op != '/' or operand.list[R][1] != 0)
编辑:
从评论中,我坚信您的操作员测试不对。如果op
是div
之类的内置函数,那么您应该执行以下操作:
from operator import div, mul, pow, add, sub
并在条件句中
(self.list[L][0] == operand.list[R][0]) and (op == mul or op == pow or op == add or op == sub or (op == div and operand.list[R][1] != 0))
,或者
(self.list[L][0] == operand.list[R][0]) and (op != div or operand.list[R][1] != 0)
答案 1 :(得分:1)
在您的课程中,您需要使用自定义行为明确重载运算符:__add__
,__sub__
,__mul__
和__div__
。否则你的数学函数不会被调用。
class LoudObject(object):
def __init__(self, val):
""" How to initialize the object with a value """
self.val = val
def __repr__(self):
""" How to represent the value when displayed """
return "LoudObject(%d)" % (self.val,)
def __add__(self, other):
print "Look! Addition!"
return LoudObject(self.val + other.val)
def __sub__(self, other):
print "Subtraction!"
return LoudObject(self.val - other.val)
def __mul__(self, other):
print "Multiplication!!!"
return LoudObject(self.val * other.val)
def __div__(self, other):
print "Division!"
if other.val == 0:
print "uh-oh, division by zero. No idea what I should do."
print "Maybe no one will notice if I return -99999999"
return LoudObject(-99999999)
return LoudObject(self.val / other.val)
现在您可以使用它:
In [2]: LoudObject(3) + LoudObject(4)
Look! Addition!
Out[2]: LoudObject(7)
In [3]: LoudObject(3) / LoudObject(4)
Division!
Out[3]: LoudObject(0)
In [4]: LoudObject(3) / LoudObject(4.0)
Division!
Out[4]: LoudObject(0.75)
In [5]: LoudObject(3) / LoudObject(0)
Division!
uh-oh, division by zero. No idea what I should do.
Maybe no one will notice if I return -99999999
Out[5]: LoudObject(-99999999)
显然这是一个玩具的例子;我不建议使用这样的类 - 并且由一个大的负哨点处理零除以后可能会导致问题。