免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 4728 | 回复: 2
打印 上一主题 下一主题

python __cmp__ 重载 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2013-06-01 11:19 |只看该作者 |倒序浏览
本帖最后由 ideal_gjh 于 2013-06-01 11:20 编辑
  1. >>>  class  Dog:
  2. ...         def  __cmp__(self,other):
  3. ... if  other  >  0  :  return  1;
  4. ... elif  other  <  0  :  return  -1;
  5. ... else:  return  0
  6. ...
  7. >>>  dog  =  Dog()
  8. >>>  if  dog  >  -10  :  print  "ok"
  9. ...
  10. >>>  if  dog  <  -10  :  print  "ok"
  11. ...
  12. ok
  13. >>>  if  dog  ==  0  :  print  "ok"
  14. ...
  15. ok
  16. >>>
复制代码
这个代码一直没有理解,有人详细解释下吗,3q.

论坛徽章:
0
2 [报告]
发表于 2013-06-01 13:35 |只看该作者
拿dog和数字比较的意义何在?

论坛徽章:
0
3 [报告]
发表于 2013-06-01 14:42 |只看该作者
回复 1# ideal_gjh


    这个例子是哪里来的啊,给你看个例子:http://www.tutorialspoint.com/python/python_classes_objects.htm
  1. Overloading Operators:
  2. Suppose you've created a Vector class to represent two-dimensional vectors. What happens when you use the plus operator to add them? Most likely Python will yell at you.

  3. You could, however, define the __add__ method in your class to perform vector addition, and then the plus operator would behave as per expectation:

  4. EXAMPLE:
  5. #!/usr/bin/python

  6. class Vector:
  7.    def __init__(self, a, b):
  8.       self.a = a
  9.       self.b = b

  10.    def __str__(self):
  11.       return 'Vector (%d, %d)' % (self.a, self.b)
  12.    
  13.    def __add__(self,other):
  14.       return Vector(self.a + other.a, self.b + other.b)

  15. v1 = Vector(2,10)
  16. v2 = Vector(5,-2)
  17. print v1 + v2
  18. When the above code is executed, it produces following result:

  19. Vector(7,8)
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP