Python Magic method.

Source: Internet
Author: User

' 123 ' + ' 456 ' 123 '. __add__. ' 456 '

In Python, these two statements are equivalent. Specifically, the second sentence is the concrete realization of the first sentence. When processing ' + ', Python will go to the ' + ' on the left side of the object to find out if there is a magic method for __add__. If this object has a specific implementation of __add__, then this object supports addition operations. ' 123 ' is a string and is also an object of type str, so we speculate that it must have a __add__ method:

>>> type (' 123 ') <type ' str ' >>>> dir (' 123 ') [' __add__ ', ' __class__ ', ' __contains__ ', ' __delattr __ ', ' __doc__ ', ' __eq__ ', ' __format__ ', ' _

Personal feeling Python Magic method is a more beautiful method, if you want to support a built-in operation, just to implement the corresponding method.

Obviously, the following code will be an error.

Class MyObject (object):    def __init__ (self, name):        self.name = Namemy_object1 = MyObject (' Hello ') My_object2 = MyObject (' world ') My_object1 + my_object2

Output:

    My_object1 + my_object2typeerror:unsupported operand type (s) for +: ' MyObject ' and ' MyObject '

After implementing the __add__ Magic method?

class MyObject (object):     def __init__ (self, name):         = name    def__add__(self, Other):        return Self.name +  = MyObject ('Hello'= MyObject (' World ' )print(My_object1 + my_object2)

Output:

HelloWorld

Python Tutor

If an object is class, then using the Dir (object) command, you can find that it has a __class__ method.

If an object supports the operation of Str (object), then it has a specific __str__ implementation.

If an object supports the operation of Len (object), then it has a specific __str__ implementation.

Python Magic method.

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.