Python 运算符重载
描述符 -http://blog.csdn.net/lis_12/article/details/53453665
特性 - http://blog.csdn.net/lis_12/article/details/53469589
方法 - http://blog.csdn.net/lis_12/article/details/53495627
__slots__
- http://blog.csdn.net/lis_12/article/details/53511300
__del__
- http://blog.csdn.net/lis_12/article/details/53647728
抽象基类 - http://blog.csdn.net/lis_12/article/details/53842299
元类 - http://blog.csdn.net/lis_12/article/details/53837491
运算符重载
在类中实现特殊方法的话,自定义对象就可以使用Python的内置方法。如定义了__add__()
,实例就能使用加法。
特殊方法主要有以下。
>>> print dir(1)
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']
example
__str__
方法创建具有良好输出格式的字符串,使用print时会主动调用这个方法。
Python所有内置数字都拥有real,imag
属性。
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Complex(object):
def __init__(self,real = 0,imag = 0):
self.real = float(real)
self.imag = float(imag)
def __sub__(self,other):
'''减'''
if issubclass(type(other),Complex) or float(other):
return Complex(self.real - other.real,self.imag - other.imag)
raise Exception('type error')
def __add__(self,other):
'''加'''
if issubclass(type(other),Complex) or float(other):
return Complex(self.real + other.real,self.imag + other.imag)
raise Exception('type error')
def __div__(self,other):
'''除'''
if (issubclass(type(other),Complex) or float(other)) and other.real != 0 and other.imag != 0:
return Complex(self.real / other.real,self.imag / other.imag)
raise Exception('type error')
def __mul__(self,other):
'''乘'''
if issubclass(type(other),Complex) or float(other):
return Complex(self.real * other.real,self.imag * other.imag)
raise Exception('type error')
def __str__(self):
return 'Complex real = %s,imag = %s'%(self.real,self.imag)
if __name__ == '__main__':
a = Complex(1,2)
b = Complex(2,3)
print a
print b
print a+b #等价于a.__add__(b)...
print a.__add__(b)
print a-b
print a*b
print a/b
b = 10
print a+b
print a-b
print a*b
#print a/b #除数为0
#b + a #等价于b.__add__(a),TypeError: unsupported operand type(s) for +: 'int' and 'Complex'
转载请标明出处(http://blog.csdn.net/lis_12/article/details/53675657).