特殊方法和运算符重载
Python类中有大量的特殊方法,其中比较常见的是构造函数(_init_())和析构函数(_del_())。
- 在python中除了构造函数与析构函数以外,还有大量的特殊方法支持更多的功能,例如运算符重载就是通过在类中重写特殊函数来实现的
Python类特殊方法
案例
- 自定义一个数组类,支持数组与数字之间的四则运算,数组之间的加法运算,内积运算和大小比较,数组元素访问和修改,以及成员测试等功能
class MyArray:
"""All the elements in this array must be numbers"""
__value = []
__size = 0
def __is_number(self, n):
if (not isinstance(n, int)) and (not isinstance(n, float)) and (not isinstance(n, complex)):
return False
return True
def __init__(self, *args):
if not args:
self.__value = []
else:
for arg in args:
if not self.__is_number(arg):
print('All elements must be numbers')
return
self.__value = list(args)
def __add__(self, n): # 数组中每个元素都与数字n相加,或两个数组相加
if self.__is_number(n):
b = MyArray()
for v in self.__value:
b.__value.append(v + n)
return b
elif isinstance(n, MyArray):
if len(n.__value) == len(self.__value):
c = MyArray()
for i, j in zip(self.__value, n.__value):
c.__value.append(i + j)
return c
else:
print("Length not equal")
else:
print("not supported")
def __sub__(self, n): # 数组中每个元素都与数字n相减,返回新数组
if not self.__is_number(n):
print(r'-operating with', type(n), 'and number type is not supported')
return
b = MyArray()
for v in self.__value:
b.__value.append(v - n)
return b
def __mul__(self, n): # 数组中每个元素都与数字n相乘,返回新数组