首页 > 其他 > 详细

Operator overloading

时间:2014-10-02 21:09:53      阅读:307      评论:0      收藏:0      [点我收藏+]

By defining other special methods, you can specify the behavior of operators on user-defined types. For example, if you define add method for the Time class, you can use the + operator on Time objects.

 def __add__(self,time):
        seconds = self.time_to_int() + time.time_to_int()
        return Time.int_to_time(seconds)

bubuko.com,布布扣

When you apply the + operator to Time objects, Python invokes __add__. When you print the result, Python invokes __str__. So there is quite a lot happening behind the scenes. Changing the behavior of an operator so that it works with user-defined types is called operator overloading. For every operator in Python there is a corresponding special method, like __add__.

 

from Thinking in Python

 

Operator overloading

原文:http://www.cnblogs.com/ryansunyu/p/4004431.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!