SoFunction
Updated on 2024-11-17

Specific uses of python __add__

__add__(), implementation logic for adding two objects of the same class, overrides +

class Myclass(object):
    def __init__(self,value):
         = value
 
    def __add__(self, other):
        return  + 
 
if __name__ == '__main__':
    o1 = Myclass(1)
    o2 = Myclass(2)
    print(o1+o2)

Print results:

3

self is only its own object, other refers to another object (belonging to the Myclass class).

Difference between "__add__" and "__iadd__" in python

Difference between "__add__" and "__iadd__", both are splice operations.

add iadd
list list
tuple

In a list, both can be used; in a tuple, only one can be used.

1. __add__ attribute

b = [7, 8, 9, 10, 11, 12]
d = [19, 20, 21, 22, 23, 24]

# The splice action is performed and the value of the splice is returned
g = b.__add__(d)
print(g)

The results of the implementation are as follows:

D:\python_env\Scripts\ F:/TESTING/BlogPosts/ReadAndWrite/list_and_tuple.py
[7, 8, 9, 10, 11, 12, 19, 20, 21, 22, 23, 24]

Process finished with exit code 0

2. __iadd__ attribute

b = [7, 8, 9, 10, 11, 12]
d = [19, 20, 21, 22, 23, 24]

# Perform splicing actions, which are spliced in situ
h = b.__iadd__(d)
print(h)

The results of the implementation are as follows:

D:\python_env\Scripts\ F:/TESTING/BlogPosts/ReadAndWrite/list_and_tuple.py
[7, 8, 9, 10, 11, 12, 19, 20, 21, 22, 23, 24]

Process finished with exit code 0

After the above two are executed, found that the results are basically the same, can not see what tricks, so we distinguish between debugging mode, at a glance . The following display:

The above figure is directly returned after executing __add__. The following figure is after the execution of __iadd__, first splice a bit and then return the value, note that it is not return out .

to this article on the specific use of python __add__() article is introduced to this, more related python __add__() use content please search for my previous articles or continue to browse the following related articles I hope you will support me more in the future!