Python中的代字号运算符 [英] The tilde operator in Python

查看:114
本文介绍了Python中的代字号运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python中的波浪号运算符有什么用途?

What's the usage of the tilde operator in Python?

我能想到的一件事是在字符串或列表的两面都做一些事情,例如检查字符串是否回文:

One thing I can think about is do something in both sides of a string or list, such as check if a string is palindromic or not:

def is_palindromic(s):
    return all(s[i] == s[~i] for i in range(len(s) / 2)) 

还有其他好的用法吗?

推荐答案

它是从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.)

这篇关于Python中的代字号运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆