6.3 Python class 运算符重载

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).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值