Type-base dispatch

Source: Internet
Author: User

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)

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 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.