目的是什么__invert__
方法?我在探索 Python 内部结构时发现:
>>> dir(__builtins__.int)
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
让我惊讶的是:
__builtins__.int().__invert__()
这似乎违反了所有数学规则,因为__builtins__.int()
返回零,我们都知道你不能反转that整数。也许我遗漏了一些东西......所以我深入研究文档并发现__invert__
相当于按位非。
-
为什么以及如何定义一个有用的object的逆作为其按位逆而不是更具语义意义的东西,非零有理数的逆是其倒数,零没有一,复数采取不同的策略,方法逆反转状态或未定义等。
有人可以举一个例子,说明按位取非的情况instance类/对象的结构在高层是有用的(即不在编译器/解释器优化级别)。
Python 文档指出对象的类型返回对象本身,那么为什么我们不能将零的反转定义为 None 或 NaN 对象呢?