python类的专有方法

来源:互联网 发布:网页中常用的js特效 编辑:程序博客网 时间:2024/06/07 00:00
一 介绍
__init__ : 构造函数,在生成对象时调用
__del__ : 析构函数,释放对象时使用
__repr__ : 打印,转换
__setitem__ : 按照索引赋值
__getitem__: 按照索引获取值
__len__: 获得长度
__cmp__: 比较运算
__call__: 函数调用
__add__: 加运算
__sub__: 减运算
__mul__: 乘运算
__div__: 除运算
__mod__: 求余运算
__pow__: 称方
 
二 举例
Python同样支持运算符重载,我么可以对类的专有方法进行重载。
  1. classVector:
  2. def __init__(self, a, b):
  3. self.a = a
  4. self.b = b
  5. def __str__(self):
  6. return'Vector (%d 和 %d)'%(self.a, self.b)
  7. def __add__(self,other):
  8. returnVector(self.a + other.a, self.b + other.b)
  9. v1 =Vector(2,10)
  10. v2 =Vector(5,-2)
  11. print(v1)
  12. print(v2)
  13. print(v1 + v2)
三 运行结果
Vector (2 和 10)
Vector (5 和 -2)
Vector (7 和 8)
 
四 运算符重载
  1. classMylist:
  2. __mylist =[]
  3. def __init__(self,*args):
  4. self.__mylist =[]
  5. for arg in args:
  6. self.__mylist.append(arg)
  7. def __add__(self,n):
  8. for i in range(0,len(self.__mylist)):
  9. self.__mylist[i]= self.__mylist[i]+ n
  10. def __sub__(self,n):
  11. for i in range(0,len(self.__mylist)):
  12. self.__mylist[i]= self.__mylist[i]- n
  13. def __mul__(self,n):
  14. for i in range(0,len(self.__mylist)):
  15. self.__mylist[i]= self.__mylist[i]* n
  16. def __div__(self,n):
  17. for i in range(0,len(self.__mylist)):
  18. self.__mylist[i]= self.__mylist[i]/ n
  19. def __mod__(self,n):
  20. for i in range(0,len(self.__mylist)):
  21. self.__mylist[i]= self.__mylist[i]% n
  22. def __pow__(self,n):
  23. for i in range(0,len(self.__mylist)):
  24. self.__mylist[i]= self.__mylist[i]** n
  25. def __len__(self):
  26. return len(self.__mylist)
  27. def show(self):
  28. print(self.__mylist)
  29. l =Mylist(1,2,3,4,5)
  30. l.show()
  31. l +5
  32. l.show()
  33. l -3
  34. l.show()
  35. l *6
  36. l.show()
  37. l %4
  38. l.show()
  39. l **3
  40. l.show()
  41. print(len(l))
  42. b =Mylist(2,3,4,5,6,7,8,9)
  43. print(len(b))
  44. b.show()
  45. b -5
  46. b.show()
  47. l.show()
五 运行结果
[1, 2, 3, 4, 5]
[6, 7, 8, 9, 10]
[3, 4, 5, 6, 7]
[18, 24, 30, 36, 42]
[2, 0, 2, 0, 2]
[8, 0, 8, 0, 8]
5
8
[2, 3, 4, 5, 6, 7, 8, 9]
[-3, -2, -1, 0, 1, 2, 3, 4]
[8, 0, 8, 0, 8]
原创粉丝点击