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