where are operators mapped to magic methods in python?

后端 未结 5 1126
無奈伤痛
無奈伤痛 2021-01-02 03:13

I\'ve been reading about magic methods in python, and I\'ve found a lot of info about overriding them and what purpose they serve, but I haven\'t been able to find where i

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-02 03:47

    dis module can somewhat help you on this:

    let's take an example of simple list:

    In [12]: def func():
        lis=[1,2,3]
        for i in range(5):
            lis+=[i]
       ....:         
    
    In [13]: def func1():
        lis=[1,2,3]
        for i in range(5):
            lis =lis + [i]
       ....:         
    
    In [14]: dis.dis(func)
      2           0 LOAD_CONST               1 (1)
                  3 LOAD_CONST               2 (2)
                  6 LOAD_CONST               3 (3)
    
                 #removed some lines of code
    
      4          34 LOAD_FAST                0 (lis)
                 37 LOAD_FAST                1 (i)
                 40 BUILD_LIST               1
                 43 INPLACE_ADD                       # += means inplace add is used
                                                      #     i.e `__iadd()__`
                 44 STORE_FAST               0 (lis)
                 47 JUMP_ABSOLUTE           28
            >>   50 POP_BLOCK           
            >>   51 LOAD_CONST               0 (None)
                 54 RETURN_VALUE        
    
    In [15]: dis.dis(func1)
      2           0 LOAD_CONST               1 (1)
                  3 LOAD_CONST               2 (2)
                  6 LOAD_CONST               3 (3)
                  9 BUILD_LIST               3
                 12 STORE_FAST               0 (lis)
                 #removed some lines of code    
      4          34 LOAD_FAST                0 (lis)
                 37 LOAD_FAST                1 (i)
                 40 BUILD_LIST               1
                 43 BINARY_ADD                          #normal binary add was used
                                                        #i.e __add__
                 44 STORE_FAST               0 (lis)
                 47 JUMP_ABSOLUTE           28
            >>   50 POP_BLOCK           
            >>   51 LOAD_CONST               0 (None)
                 54 RETURN_VALUE        
    

提交回复
热议问题