一:特殊方法和运算符重载
Python的运算符实际上是通过调用对象的特殊方法实现的。比如:
#运算符-特殊方法 a = 20 b = 30 c = a + b d = a.__add__(b) print(‘c=‘,c) print(‘d=‘,d)
运行结果:
c= 50
d= 50
常见的特殊方法统计如下:
每个运算符实际上都对应了相应的方法,统计如下:
我们可以重写上面的特殊方法,即实现了“运算符的重载”。
【操作】运算符的重载
#测试运算符的重载 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)
运行结果:
jack-----jason
jackjackjackjackjack
二:特殊属性
Python对象中包含了很多双下划线开始和结束的属性,这些是特殊属性,有特殊用法。常见的特殊属性:
【操作】特殊属性
#测试特殊属性 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‘>]
原文地址:https://www.cnblogs.com/jack-zh/p/10850094.html