魚C-python之函數(shù)-變量、內(nèi)置函數(shù)、閉包

#####1.局部變量&全局變量
局部變量是在函數(shù)內(nèi)部定義的,全局變量是在函數(shù)的外部定義的,在函數(shù)的內(nèi)部可以訪問全局變量,但是不要試圖去修改全局變量,這樣函數(shù)會(huì)在函數(shù)體內(nèi)創(chuàng)建一個(gè)和全局變量名字一樣的局部變量。

例子程序:
def discouts(price,rate):
    final_price = price * rate
    old_price = 50
    print('修改后的old_price的值是1:',old_price)
    return final_price;

old_price = float(input('請輸入原價(jià):'))
rate = float(input('請輸入折扣率:'))
new_price = discouts(old_price,rate)
print('修改后的old_price 的值是2:',old_price)
print('打折后的價(jià)格是:',new_price)
結(jié)果:
==================== RESTART: D:/Python35/c/function1.py ====================
請輸入原價(jià):100
請輸入折扣率:0.8
修改后的old_price的值是1: 50
修改后的old_price 的值是2: 100.0
打折后的價(jià)格是: 80.0
>>>

根據(jù)程序運(yùn)行的結(jié)果可得到,在函數(shù)的內(nèi)部修改全局變量是不起作用的。

如果你真想在函數(shù)內(nèi)修改全局變量,那就在修改前加一句

global 變量
2.內(nèi)嵌函數(shù)

即在函數(shù)1的內(nèi)部定義一個(gè)函數(shù)2,但是函數(shù)2只能在函數(shù)1里面調(diào)用,出了函數(shù)1就不能調(diào)用啦。

3.閉包

閉包需滿足2點(diǎn):
1.在函數(shù)1的內(nèi)部定義一個(gè)函數(shù)2
2.函數(shù)2引用了函數(shù)1 定義的參數(shù)
注意:閉包是在內(nèi)置函數(shù)基礎(chǔ)上的,所以函數(shù)2也不能在函數(shù)1的外部被調(diào)用
例子:

>>> def FunX(x):
    def FunY(y):
        return x * y
    return FunY

>>> i=FunX(8)
>>> i
<function FunX.<locals>.FunY at 0x0000000003593840>
>>> type(i)
<class 'function'>
>>> i(5)
40
>>> FunX(8)(5)
40
>>> 

如果變量在函數(shù)1里面被賦值,在函數(shù)2里面又想使用,要在 函數(shù)2使用變量前 對(duì)變量進(jìn)行

nonlocal 變量
>>> def Fun1():
    x = 5
    def Fun2():
        x *= x
        return x
    return Fun2()

>>> Fun1()
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    Fun1()
  File "<pyshell#6>", line 6, in Fun1
    return Fun2()
  File "<pyshell#6>", line 4, in Fun2
    x *= x
UnboundLocalError: local variable 'x' referenced before assignment
>>> def Fun1():
    x = 5
    def Fun2():
        nonlocal x   
        x *= x
        return x
    return Fun2()

>>> Fun1()
25
>>> 
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容