return, return None, and no return at all?

后端 未结 5 639
时光取名叫无心
时光取名叫无心 2020-11-22 01:07

Consider three functions:

def my_func1():
  print \"Hello World\"
  return None

def my_func2():
  print \"Hello World         


        
5条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 01:43

    Yes, they are all the same.

    We can review the interpreted machine code to confirm that that they're all doing the exact same thing.

    import dis
    
    def f1():
      print "Hello World"
      return None
    
    def f2():
      print "Hello World"
      return
    
    def f3():
      print "Hello World"
    
    dis.dis(f1)
        4   0 LOAD_CONST    1 ('Hello World')
            3 PRINT_ITEM
            4 PRINT_NEWLINE
    
        5   5 LOAD_CONST    0 (None)
            8 RETURN_VALUE
    
    dis.dis(f2)
        9   0 LOAD_CONST    1 ('Hello World')
            3 PRINT_ITEM
            4 PRINT_NEWLINE
    
        10  5 LOAD_CONST    0 (None)
            8 RETURN_VALUE
    
    dis.dis(f3)
        14  0 LOAD_CONST    1 ('Hello World')
            3 PRINT_ITEM
            4 PRINT_NEWLINE            
            5 LOAD_CONST    0 (None)
            8 RETURN_VALUE      
    

提交回复
热议问题