Dunder methods & operator overloading

link:https://www.python-course.eu/python3_magic_methods.php

Dunder methods refers to special methods with fixed names, such as '_ init _'.

So what's magic about the _ init _ method? The answer is, you don't have to invoke it directly. The invocation is realized behind the scenes. When you create an instance x of a class A with the statement "x = A()", Python will do the necessary calls to _ new _ and _ init _.

We have encountered the concept of operator overloading many times in the course of this tutorial. We had used the plus sign to add numerical values, to concatenate strings or to combine lists:

>>> 4 + 5
9
>>> 3.8 + 9
12.8
>>> "Peter" + " " + "Pan"
'Peter Pan'
>>> [3,6,8] + [7,11,13]
[3, 6, 8, 7, 11, 13]
>>> 

It's even possible to overload the "+" operator as well as all the other operators for the purposes of your own class. To do this, you need to understand the underlying mechanism. There is a special (or a "magic") method for every operator sign. The magic method for the "+" sign is the _ add _ method. For "-" it is "sub" and so on. We have a complete listing of all the magic methods a little bit further down.

Dunder methods & operator overloading_第1张图片
image.png

The mechanism works like this: If we have an expression "x + y" and x is an instance of class K, then Python will check the class definition of K. If K has a method add it will be called with x.add(y), otherwise we will get an error message.

Traceback (most recent call last):
  File "", line 1, in 
TypeError: unsupported operand type(s) for +: 'K' and 'K'

Overview of Magic Methods(Dunder Methods)

Dunder methods & operator overloading_第2张图片
image.png
Dunder methods & operator overloading_第3张图片
image.png
Dunder methods & operator overloading_第4张图片
image.png
Dunder methods & operator overloading_第5张图片
image.png
_ iadd _
class A:
    def __init__(self,age):
        self.age = age

    def __len__(self):
        pass

    def __floordiv__(self, other):pass

    def __truediv__(self, other):
        return self.age / other.age

    def __iadd__(self, other):
        return self.age + other.age


a1 = A(13)
b1 = A(13)
a1+=b1

print(a1)  #26

你可能感兴趣的:(Dunder methods & operator overloading)