首页 > 代码库 > Operator overloading
Operator overloading
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)
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。