Python 函數及常用模組 - 裝飾器前奏(函數就是變量)

函數就是變量

下面就用代碼來解釋一下 函數即變量 是什麼意思!

觀察一下這個代碼,能不能正常執行?

#!/usr/bin/env python3
# -*- coding:utf-8 -*-

def foo():
    print('in the foo')
    bar()
    
foo()

---------------執行結果---------------

Traceback (most recent call last):
  File "/Python/project/path/decorator1.py", line 9, in <module>
    foo()
  File "/Python/project/path/decorator1.py", line 7, in foo
    bar()
NameError: name 'bar' is not defined
in the foo

Process finished with exit code 1

嗯!發現出現了一個錯誤 NameError: name 'bar' is not defined , 這是因為 bar 這個函數沒有被定義,所以才會報錯,那要怎麼解決這問題呢!?其實很簡單,就在寫一個函數叫 bar 就行了,那我們來寫寫看吧!

  • 寫法一: 把bar函數定義在foo函數之前,看看能不能正常執行?
#!/usr/bin/env python3
# -*- coding:utf-8 -*-

def bar():
    print('in the bar')

def foo():
    print('in the foo')
    bar()

foo()

---------------執行結果---------------

in the foo
in the bar

Process finished with exit code 0
  • 寫法二: 把bar函數定義在foo函數之後,看看能不能正常執行?
#!/usr/bin/env python3
# -*- coding:utf-8 -*-

def foo():
    print('in the foo')
    bar()
    
def bar():
    print('in the bar')

foo()

---------------執行結果---------------

in the foo
in the bar

Process finished with exit code 0
  • 寫法三: 把bar函數寫在foo函數調用之後
#!/usr/bin/env python3
# -*- coding:utf-8 -*-

def foo():
    print('in the foo')
    bar()
    
foo()

def bar():
    print('in the bar')
    
---------------執行結果---------------

in the foo
Traceback (most recent call last):
  File "/Python/project/path/decorator1.py", line 9, in <module>
    foo()
  File "/Python/project/path/decorator1.py", line 7, in foo
    bar()
NameError: name 'bar' is not defined

Process finished with exit code 1

耶~!怎麼第三個寫法會報錯?

解說概念:

寫法一圖解說明

寫法二圖解說明

寫法三圖解說明

總結

寫法一跟寫法二,都是在調用函數之前,就已經先定義函數好,所以都能正常執行,而寫法三會報錯,就是因為bar函數,是在調用函數之後,所以還沒有被定義,才無法正常執行,因此也証明了 函數即變量

posted @ 2017-06-02 00:27  丹尼爾  阅读(138)  评论(0编辑  收藏  举报