编辑布尔值和运算符

问题描述 投票:4回答:2

所以我一直在搞乱类中的标准运算符,试着看看我能做些什么,但是我还没能找到如何编辑boolean and运算符。

我可以通过定义&编辑按位__and__(self)operator,但不能编辑and的行为方式。有谁知道我怎么能改变a and b的行为abare我正在制作的类的实例?

提前致谢!

python boolean operators
2个回答
5
投票

在Python 2中,andor访问__nonzero__

>>> class Test(object):
...     def __nonzero__(self):
...         print '__nonzero__ called'
...         return True
... 
>>> Test() and 1
__nonzero__ called
1

在Python 3中,__nonzero__已更名为__bool__

>>> class Test:
...     def __bool__(self):
...         print('__bool__ called')
...         return True
... 
>>> Test() and 1
__bool__ called
1

请注意,短路评估可能会抑制对__nonzero____bool__的调用。

>>> 0 and Test()
0
>>> 1 or Test()
1

需要注意的另一个特性是,如果没有定义__len__ / __nonzero__,Python正试图访问__bool__,如果__len__返回0以外的值,则将对象视为真实。如果两种方法都已定义,则__nonzero__ / __bool__获胜。

>>> class Test:
...     def __len__(self):
...         return 23
... 
>>> Test() and True
True
>>>
>>> class Test:
...     def __len__(self):
...         return 23
...     def __bool__(self):
...         return False
... 
>>> Test() and True
<__main__.Test object at 0x7fc18b5e26d8> # evaluation stops at Test() because the object is falsy
>>> bool(Test())
False

有什么方法可以让这个回归除了布尔之外的其他东西,比如说,一个布尔列表?

很不幸的是,不行。 documentation声明该方法应该返回FalseTrue,但实际上如果你让它返回别的东西,你会得到一个TypeError

>>> class Test:
...     def __bool__(self):
...         return 1
... 
>>> Test() and 42
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __bool__ should return bool, returned int
>>> 
>>> bool(Test())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __bool__ should return bool, returned int

4
投票

and运算符使用__bool__将第一个操作数转换为布尔值,然后对布尔值执行预定义的操作(如果first.__bool__()True,则返回第二个,否则返回第一个)。没有办法改变这种行为。

© www.soinside.com 2019 - 2024. All rights reserved.