python - 在 Python 中覆盖 'not' 运算符

标签 python operator-overloading operators

我找不到与not x 运算符对应的方法。不过,andorxor 有一个。它在哪里?

3. Data model

最佳答案

andor 运算符没有钩子(Hook),没有(因为它们短路),并且没有 xor 运算符Python。 __and____or__ 用于 bitwise & and | operators , 分别。 not 的等效位运算符是 ~(反转),它由 __invert__ method 处理, 而 __xor__涵盖了 ^ 按位运算符。

nottruth-value of an object 上运行.如果你有一个容器,给它一个 __len__ method , 如果不给它 __bool__ method .咨询其中任何一个以确定一个对象是否应该被认为是“真实的”; not 反转该测试的结果。

因此,如果 __bool__ 返回 True__len__ 返回 0 以外的整数, 会将其反转为 False,否则 not 会生成 True。请注意,您不能让 not 返回除 bool 值以外的任何其他内容!

来自 __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.>

对于 not 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.

大胆强调我的

关于python - 在 Python 中覆盖 'not' 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39754808/

相关文章:

c++ - C++类中的运算符重载函数

dart - 是否可以让运算符在运算中使用先验值

在数学语句中保留 << 和 >> 的 C++ 到 VB.NET 的转换

python - Flask SQLAlchemy 无法将表情符号插入 MySQL

python - 在 python 中演奏和弦

python - zsh:在 zsh 脚本中的heredoc之后转义换行符

c++ - 运算符重载失败,运算符 [] 和运算符强制转换为 int

c++ - C++中的赋值运算符重载

javascript - 为什么 typeof 称为运算符而不是函数?

python - 如何在python中从文件中提取数据