我正在寻求有关如何“接近”使and
运算符超载的建议。提示我在做什么的代码示例:
import operator
OP = { operator.ge: ">=", operator.le: "<=" }
class Expression(object):
def __init__(self, left, right, op):
self.left = left
self.right = right
self.op = op
def __le__(self, other):
return Expression(self, other, operator.le)
def __ge__(self, other):
return Expression(self, other, operator.ge)
def __str__(self):
return "(%s %s %s)" % (self.left, OP[self.op], self.right)
def __repr__(self):
return "<Expression: %s %s %s>" % (self.left, self.op, self.right)
class Variable(Expression):
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def __repr__(self):
return "<Variable: %s>" % self.name
def _and(left, right):
return (left, right)
print 1 <= Variable("x") <= 3
print _and(1 <= Variable("x"), Variable("x") <= 3)
上面的示例打印:
(x <= 3)
(<Expression: x <built-in function ge> 1>, <Expression: x <built-in function le> 3>)
根据Python 文档,表达式1 <= a <= 2
转换为1 <= a and a <= 2
,所以我猜测在我的示例中1 <= Variable("x")
计算结果为,True
因此表达式返回 的值Variable("x") <= 3
。我需要一种方法来分别获取两个表达式 ( 1 <= a
, 和a <= 2
),最好不要两次写出中间表达式(就像我对 _and 函数所做的那样),因为中间表达式可能非常复杂且麻烦两次(我意识到我可以将其保存到变量中并使用它,但这也不太可读)。根据this SE postand
运算符不能重载,所以我要问的是是否可以这样做,然后如何,或者我是否必须将比较分成两部分(指定中间表达式两次)。任何正确方向的建议表示赞赏!谢谢你。
可能相关:
编辑:所以我基本上做的是为线性程序写出约束,所以我的代码的相关部分目前看起来像这样:
model.add_constr(a <= b)
model.add_constr(b <= c)
# now i could alter add_constr to support either a tuple or two arguments enabling:
model.add_constr(a <= b, b <= c)
model.add_constr((a <= b, b <= c))
# but most pleasing would be if I could do
model.add_constr(a <= b <= c)
# that would return for example a two tuple that could be interpreted appropriately by
# add_constr()