python的操作符重载

来源:互联网 发布:unity 模型 优化 插件 编辑:程序博客网 时间:2024/06/05 04:11

列出一些常用的:

 

1. __call__

定义了__call__方法的类实例,可以像一个函数一样被“调用”

 

class tester:

  def __init__(self, start):

    self.state = start

  def __call__(self, label):

    print(label,self.state)

    self.state += 1

 

H = tester(99)

H('juice')

juice 99

 

H('pancakes')

pancakes 100

 

2. __str__

Class 的__str__方法类似于java对象的toString()方法

 

3. __init__, __del__

初始化函数和构造函数

 

4. __eq__, __ne__, __lt__, __le__, __gt__, __ge__

==, !=, <=, <, >, >=

 

5. __getitem__

使用x[key]索引操作符

 

6. __len__

对序列对象使用len()

 

7. __add__,__radd__

对象左+和右+

 

8. __contains__

测试是否包含某个元素

 

...