例:
class Circle:
__radius=0
def __init__(self,radius):
self.__radius=radius
def getRadius(self):
return self.__radius
def __add__(self,pther)
return Circle(self.__radius+other.__radius)
c1=Circle(12)
c2=Circle(9)
c3=c1+c2 #相加时,会自动调用上面定义的__add__方法
print(c3.getRadius()) #21
其他操作符重载
运算符 | 方法名 | 说明 |
+ | __add__(self,other) | 加 |
- | __sub__(self,other) | 减 |
* | __mul__(self,other) | 乘 |
/ | __truediv__(self,other) | 除 |
< | __lt__(self,other) | 小于 |
> | __gt__(self,other) | 大于 |
<= | __le__(self,other) | 小于等于 |
>= | __ge__(self,other) | 大于等于 |
== | __eq__(self,other) | 相等 |
!= | __ne__(self,other) | 不等 |
[] | __getitem__(self,other) | 索引 |
in | __contains__(self,other) | 包含 |
len | __len__(self,other) | 个数 |
str() | __str__(self,other) | 转为字符串 |