美文网首页
Dunder methods & operator overlo

Dunder methods & operator overlo

作者: whenitsallover | 来源:发表于2018-03-26 23:28 被阅读0次

    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
    

    相关文章

      网友评论

          本文标题:Dunder methods & operator overlo

          本文链接:https://www.haomeiwen.com/subject/sivdcftx.html