1 class Prod:
2 def __init__(self, value):
3 print '111'
4 self.value = value
5 def __call__(self, other):
6 print '222'
7 self.value * other
8 return self
9 def printa(self):
10 print self.value
11
12 p = Prod(2)(10)
13 p.printa()
先调用init,在(10)的时候调用call
注意8行要返回self,负责13行会出错
在Python语言中提供了类似于C++的运算符重在功能:
一下为Python运算符重在调用的方法如下:
Method Overloads Call for
__init__ 构造函数 X=Class()
__del__ 析构函数 对象销毁
__add__ + X+Y,X+=Y
__or__ | X|Y,X|=Y
__repr__ 打印转换 print X,repr(X)
__str__ 打印转换 print X,str(X)
__call__ 调用函数 X()
__getattr_ 限制 X.undefine
__setattr__ 取值 X.any=value
__getitem__ 索引 X[key],
__len__ 长度 len(X)
__cmp__ 比较 X==Y,X<Y
__lt__ 小于 X<Y
__eq__ 等于 X=Y
__radd__ Right-Side + +X
__iadd__ += X+=Y
__iter__ 迭代 For In
2 def __init__(self, value):
3 print '111'
4 self.value = value
5 def __call__(self, other):
6 print '222'
7 self.value * other
8 return self
9 def printa(self):
10 print self.value
11
12 p = Prod(2)(10)
13 p.printa()
先调用init,在(10)的时候调用call
注意8行要返回self,负责13行会出错
在Python语言中提供了类似于C++的运算符重在功能:
一下为Python运算符重在调用的方法如下:
Method Overloads Call for
__init__ 构造函数 X=Class()
__del__ 析构函数 对象销毁
__add__ + X+Y,X+=Y
__or__ | X|Y,X|=Y
__repr__ 打印转换 print X,repr(X)
__str__ 打印转换 print X,str(X)
__call__ 调用函数 X()
__getattr_ 限制 X.undefine
__setattr__ 取值 X.any=value
__getitem__ 索引 X[key],
__len__ 长度 len(X)
__cmp__ 比较 X==Y,X<Y
__lt__ 小于 X<Y
__eq__ 等于 X=Y
__radd__ Right-Side + +X
__iadd__ += X+=Y
__iter__ 迭代 For In