且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python中的代字号运算符

更新时间:2023-02-04 14:31:37

它是从C借来的一元运算符(采用单个参数),其中所有数据类型只是解释字节的不同方式.这是取反"或补码"操作,其中输入数据的所有位都取反.

It is a unary operator (taking a single argument) that is borrowed from C, where all data types are just different ways of interpreting bytes. It is the "invert" or "complement" operation, in which all the bits of the input data are reversed.

在Python中,对于整数,二进制补码表示形式的位将整数取反(如每个单独的位在b <- b XOR 1中一样),结果再次解释为二进制补码整数.因此对于整数,~x等效于(-x) - 1.

In Python, for integers, the bits of the twos-complement representation of the integer are reversed (as in b <- b XOR 1 for each individual bit), and the result interpreted again as a twos-complement integer. So for integers, ~x is equivalent to (-x) - 1.

~运算符的形式化形式作为operator.invert提供.要在您自己的类中支持此运算符,请给它一个__invert__(self)方法.

The reified form of the ~ operator is provided as operator.invert. To support this operator in your own class, give it an __invert__(self) method.

>>> import operator
>>> class Foo:
...   def __invert__(self):
...     print 'invert'
...
>>> x = Foo()
>>> operator.invert(x)
invert
>>> ~x
invert

在某个实例中具有相同实例的互补"或逆"含义的任何类都是反转运算符的可能候选对象.但是,如果使用不当,运算符重载会导致混乱,因此请确保在向您的类提供__invert__方法之前这样做确实是有道理的. (请注意,字节字符串[ex:'\xff']不支持此运算符,即使将字节字符串的所有位取反也很有意义.)

Any class in which it is meaningful to have a "complement" or "inverse" of an instance that is also an instance of the same class is a possible candidate for the invert operator. However, operator overloading can lead to confusion if misused, so be sure that it really makes sense to do so before supplying an __invert__ method to your class. (Note that byte-strings [ex: '\xff'] do not support this operator, even though it is meaningful to invert all the bits of a byte-string.)