gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 19:54:09 25 4
gpt4 key购买 nike

我找不到与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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com