Python的運算符其實是經過調用對象的特殊方法實現的。好比:ssh
#運算符-特殊方法 a = 20 b = 30 c = a + b d = a.__add__(b) print('c=',c) print('d=',d)
運行結果:測試
c= 50
d= 50spa
常見的特殊方法統計以下:3d
每一個運算符實際上都對應了相應的方法,統計以下:code
咱們能夠重寫上面的特殊方法,即實現了「運算符的重載」。orm
【操做】運算符的重載對象
#測試運算符的重載 class Person: def __init__(self,name): self.name = name def __add__(self, other): if isinstance(other,Person): return '{0}-----{1}'.format(self.name,other.name) else: return '不是同類對象不能相加' def __mul__(self, other): if isinstance(other,int): return self.name*other else: return '不是同類對象不能相加' p1 = Person('jack') p2 = Person('jason') print(p1 + p2) print(p1*5)
運行結果:blog
jack-----jason
jackjackjackjackjackget
Python對象中包含了不少雙下劃線開始和結束的屬性,這些是特殊屬性,有特殊用法。常見的特殊屬性:hash
【操做】特殊屬性
#測試特殊屬性 class A: pass class B: pass class C(B,A): def __init__(self,nn): self.nn = nn def cc(self): print('cc') c1 = C(5) print(dir(c1)) print(c1.__dict__) print(c1.__class__) print(C.__bases__) print(C.mro()) print(A.__subclasses__())
運行結果:
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'cc', 'nn'] {'nn': 5} <class '__main__.C'> (<class '__main__.B'>, <class '__main__.A'>) [<class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>] [<class '__main__.C'>]