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.

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 "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'K' and 'K'

Overview of Magic Methods(Dunder Methods)

image.png
image.png
image.png
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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容