码迷,mamicode.com
首页 > 其他好文 > 详细

Type-base dispatch

时间:2014-10-03 00:43:13      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   ar   for   sp   div   

In the previous section we added two Time objects, but you also might want to add an integer to a Time object. The following is an alternative version of __add__ that checks the type of other and invokes either add_time or increment:

def __add__(self,other):
        if (isinstance(other,Time)):
            return self.increment(other)
        else:
            return Time.int_to_time(self.time_to_int() + other)

bubuko.com,布布扣

The built-in function isinstance takes a value and a class object, and returns True if the value is an instance of the class. If other is a Time object, __add__ invokes add_time. Otherwise it assumes that the seconds parameter is a number and invokes increment. This operation is called a type-based dispatch because it dispatches because it dispatches the computation to different methods based on the type of the arguments.

Unfortunately, this implementation of addition is not commutative. If the integer is the first operand. The problem is, instead of asking the Time object to add an integer, Python is asking an integer to add a Time object, and it doesn’t know how to do that. But there is a clever solution for this problem, the radd method, which stands for ‘right-side add’. This method is invoked when a Time object appears on the right side of the + operator.

def __radd__(self,other):
        return self.__add__(other)

 

from Thinking in Python

Type-base dispatch

标签:style   blog   http   color   io   ar   for   sp   div   

原文地址:http://www.cnblogs.com/ryansunyu/p/4004519.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!