【发布时间】:2019-09-26 20:57:16
【问题描述】:
给定以下类:
import operator
class Foo(object):
def __init__(self, bah):
self.bah = bah
def __invert__(self):
return {'not': self.bah}
def __repr__(self):
return self.bah
def __or__(self, other):
return {'or': [self.bah, other]}
x = Foo('obj1')
y = Foo('obj2')
我能做到:
operator.inv(x) # ~x
这给了我:
{'not': 'obj1'}
我能做到:
operator.or_(x, ~y) # x | ~y
这给了我:
{'or': ['obj1', {'not': 'obj2'}]}
但为什么我做不到:
operator.or_(~x, y) # ~x | y
这会引发以下错误:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-175-92fdd35dc3b3> in <module>
----> 1 operator.or_(~x, y)
TypeError: unsupported operand type(s) for |: 'dict' and 'Foo'
我怎样才能输出以下内容?
{'or': [{'not': 'obj1'}, 'obj2']}
【问题讨论】:
-
您的运算符应该返回
Foo的实例,以便您可以在它们上调用更多运算符。 -
or运算符从左侧计算其操作数。~x首先被评估,然后or被应用。由于~x从您在Foo类中的定义中返回dict,因此or将应用于dict和未定义的Foo。参考:docs.python.org/3/reference/expressions.html#or
标签: python bitwise-operators operator-keyword bitwise-or