重写Python中的not运算符

2024-10-02 14:21:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我找不到与not x运算符对应的方法。有一个代表and,or,xortho。它在哪里? https://docs.python.org/3/reference/datamodel.html


Tags: orand方法httpsorgdocshtmlnot
2条回答

There is one for and,or,xor tho

您看到的方法是针对&|,和{},而不是andor,或{}(这甚至不是Python运算符)。在

not不能重载,就像and和{}不能重载一样。按位~可以重载;这是__invert__。在

如果您希望能够重载not,那么您要么只能使用重载~,要么必须编写自己的logical_not函数,并使用它来代替not运算符。在

在Python中没有andor运算符的钩子,没有(因为它们短路),而且Python中也没有xor运算符。__and__和{}分别用于bitwise ^{} and ^{} operatorsnot的等价位运算符是~(反转),它由^{} method处理,而^{}覆盖了{}位运算符。在

not操作truth-value of an object。如果你有一个容器,给它一个^{} method,如果没有,给它一个^{} method。任何一个都会被咨询,以确定一个对象是否应该被认为是“true”;not反转该测试的结果。在

因此,如果__bool__返回True__len__返回0以外的整数,not会将其转换为False,否则{}生成{}。请注意,您不能使not只返回布尔值!在

来自__bool__的文档:

__bool__
Called to implement truth value testing and the built-in operation bool(); should return False or True. When this method is not defined, __len__() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither __len__() nor __bool__(), all its instances are considered true.>

对于^{} expression

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. User-defined objects can customize their truth value by providing a __bool__() method.

The operator not yields True if its argument is false, False otherwise.

bold emphasis我的。在

相关问题 更多 >