溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

39 py函數(shù)作用域遞歸函數(shù) 變量作用域局部函數(shù) 使用lam

發(fā)布時間:2020-02-25 16:38:10 來源:網(wǎng)絡(luò) 閱讀:287 作者:馬吉輝 欄目:大數(shù)據(jù)
第十課:函數(shù)作用域
// python 中的嵌套函數(shù)  在一個函數(shù)中再定義一個函數(shù)
# 小結(jié) :
# 函數(shù)作用域:因為:python是動態(tài)語言,定義變量的時候是不需要指定變量類型的,這樣的話,我們在使用或者定義變量的時候作用域會分不清
# 如果在函數(shù)中定義一個變量,而且變量名和該函數(shù)上一級的作用域中的變量名相同
# 那么在該函數(shù)使用該變量時,就會使用局部變量
# 如果在函數(shù)中使用一個變量,但該變量在函數(shù)中并沒有定義,那么會到該函數(shù)上一層的作用域去尋找該變量,如果還沒有找到,會繼續(xù)到上一層作用域去尋找,如果沒找到會拋出變量未定義異常
x = 10          # 定義了一個變量 并賦值 
def fun1():
    x = 100
fun1()
print(x)         # 10

y = 123
def fun2():
    print(y)
fun2()            # 123 在函數(shù)中,如果在函數(shù)體中沒有定義變量的話,首先會在函數(shù)體中去找 變量的值,如果沒有,就找全局的作用域去找  

n = 332
def fun3():
    n = 4
    print(n)
fun3()            # 4   這個和第一個例子有什么區(qū)別呢? 多了一個 print(n) 其實這個就是局部作用域,在調(diào)用函數(shù)的時候就已經(jīng)算出值了。

def fun4():
    print(n)
    n = 100
# fun4()  拋出異常

# 定義一個嵌套函數(shù) 
m = 10
def fun5():
    # m = 100
    def fun6():
        print(m)
        print('fun6')
    return fun6           # 反映 函數(shù)的引用 
fun5()()           # 100 fun6   調(diào)用函數(shù)fun6的引用      比如在fun6這個函數(shù)中沒有定義m 那么就會在上一層 m = 100 找 找到了100 那么就輸出100 接下來 如果注釋掉m = 100 那么就需要去上一層再找 找了 m = 10 那么就輸出10    如果再注釋了,那么就找不到了 就會報錯

----------------------------------------------------------
第11課:函數(shù)的遞歸
# 函數(shù)遞歸:在一個函數(shù)中調(diào)用函數(shù)本身    自己調(diào)用自己 

# 階乘
# n! = 1 * 2 * 3 * ... *n
# n! = (n - 1)! * n  n == 0 or n == 1
def jc(n):
    # 終止條件
    if n == 0 or n == 1:
        return 1           # 返回結(jié)果為1 
    else:
        return jc(n - 1) * n
print(jc(10))   # 3628800

# 斐波那契數(shù)列   : 當(dāng)前的數(shù)列值,表示前2項數(shù)列之和
# 0 1 1 2 3 5 8 13 21 
# f(n) = f(n - 1) + f(n - 2)   
# n == 0  return 0    n == 1 return 1
def fibnonacci(n):
    # 終止條件
    if n == 0:
        return 0      # 直接返回0
    elif n == 1:
        return 1      # 直接返回1 
    else:
        return fibnonacci(n - 1) + fibnonacci(n - 2)

print(fibnonacci(8))    # 21 

--------------------------------------------------------------------------
第十四課: python變量作用域
局部變量: 比如在函數(shù)體內(nèi) 有用 
全局變量: 在整個范圍內(nèi)都有用
在py中有3個函數(shù) 可以獲取局部變量和全局變量
globals: 獲取全局范圍內(nèi)所有的變量
locals: 獲取當(dāng)前作用域內(nèi)的所有變量
vars(object): 獲取指定對象范圍內(nèi)所有的變量,如果不指定object ,vars和locals的作用是完全一樣的

def hanshu():
    name = 'majihui'
    age = 30
    print(name,age)    # majihui 30
    print(locals())    # {'name': 'majihui', 'age': 30} 轉(zhuǎn)化為了字典
    #print(globals())  #{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fb62815d7b8>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Users/majihui/pycharm_work/test07.py', '__cached__': None, 'hanshu': <function hanshu at 0x7fb6280dc268>}
    # 全局變量輸出的什么鬼,太多了
    print(vars())      # {'name': 'majihui', 'age': 30}
    #print(vars(object)) # {'__repr__': <slot wrapper '__repr__' of 'object' objects>, '__hash__': <slot wrapper '__hash__' of 'object' objects>, '__str__': <slot wrapper '__str__' of 'object' objects>, '__getattribute__': <slot wrapper '__getattribute__' of 'object' objects>, '__setattr__': <slot wrapper '__setattr__' of 'object' objects>, '__delattr__': <slot wrapper '__delattr__' of 'object' objects>, '__lt__': <slot wrapper '__lt__' of 'object' objects>, '__le__': <slot wrapper '__le__' of 'object' objects>, '__eq__': <slot wrapper '__eq__' of 'object' objects>, '__ne__': <slot wrapper '__ne__' of 'object' objects>, '__gt__': <slot wrapper '__gt__' of 'object' objects>, '__ge__': <slot wrapper '__ge__' of 'object' objects>, '__init__': <slot wrapper '__init__' of 'object' objects>, '__new__': <built-in method __new__ of type object at 0x1034b15e8>, '__reduce_ex__': <method '__reduce_ex__' of 'object' objects>, '__reduce__': <method '__reduce__' of 'object' objects>, '__subclasshook__': <method '__subclasshook__' of 'object' objects>, '__init_subclass__': <method '__init_subclass__' of 'object' objects>, '__format__': <method '__format__' of 'object' objects>, '__sizeof__': <method '__sizeof__' of 'object' objects>, '__dir__': <method '__dir__' of 'object' objects>, '__class__': <attribute '__class__' of 'object' objects>, '__doc__': 'The most base type'}
    # 輸出的什么鬼
    print(locals()['age'])  # 30
    locals()['age'] = 50    # 嘗試去修改,結(jié)果為 不會去修改參數(shù)值 并不是變量本身
    print(age)              # 30

hanshu()

x = 20
y = 40

print(globals()['x'])    # 20

#我們接下來,可以定義一個對象
class myclass():
    def __init__(self):
        self.name = 'majihui'
print(vars(myclass()))        # {'name': 'majihui'}

#如何在一個函數(shù)中使用全局變量
value = 100
def a():
    value = 200     # 定義了一個新的局部變量
    print(value)
a()                 # 200

-------------------------------------------------------------------------
第十五課:局部函數(shù)
局部變量只在函數(shù)的內(nèi)部起作用,
局部函數(shù)和局部的變量是一樣的,只有在函數(shù)的內(nèi)部才能被定義,才能被調(diào)用

def process(type,n):
    def pinfang(n):
        return n * n
    def lifang(n):
        return n * n * n
    def add(n):
        return n + n

    if type == 'pinfan':
        return pinfang(n)
    elif type == 'lifang':
        return  lifang(n)
    else:
        return add(n)

print(process('pinfang',10))     
print(process('lifang',10))
print(process('add',10))
結(jié)果為:
20
1000
20

def xyz():
    name = 'majihui'
    def x():
        #print(name)
        name = 'mjh'
        print(name)
    x()
xyz()    # mjh

def xyz():
    name = 'majihui'
    def x():
        nonlocal name
        print(name)
        name = 'mjh'
        #print(name)
    x()
xyz()    # majihui 

----------------------------------------------------------------------
第十六課 使用函數(shù)變量
在python語言中,可以將函數(shù)當(dāng)成一個變量使用,可以將一個函數(shù)傅給變量

# 這一步將一個函數(shù)付給另外一個變量的方式
def pow(base,exponent):
    result = 1
    for i in range(1,exponent +1):
        result *= base
    return result

print(pow(2,10))   # 1024 

f = pow

print(f(3,10))   # 59049 

# 將函數(shù)本身最為一個參數(shù)
def area(width,height):
    return width * height
f = area

print(f(3,4))  # 12

# 這個area函數(shù)也可以作為一個函數(shù)的參數(shù)

def process(fun,a1,a2):
    return fun(a1,a2)

print(process(pow,4,5))    # 1024
print(process(area,10,20))  # 200 

# 將函數(shù)本身作為一個返回值
print("-----------")
def process1(type):
    def square(n):
        return n * n
    def add(n,m):
        return n + m
    if type == 'square':
        return square
    else:
        return add

print(process1('square')(12))     # 144
print(process1('add')(12,43))      # 55

---------------------------------------------------------------------
第十七課 使用lambda表達(dá)式代替局部函數(shù)
# 使用lambda表達(dá)式代替局部函數(shù)
# lambda表達(dá)式本身就是一個表達(dá)式,這個表達(dá)式他可傳入一個參數(shù),可以有1行的執(zhí)行代碼
# 他實際上就是一個簡化的函數(shù)

def get_math_func(type):
    if type == 'sequare':
        return lambda n:n * n
    elif type == 'cube':
        return lambda n:n * n * n
    else:
        return lambda n:n + n

math_func01 = get_math_func('sequare')
print(math_func01(10))                              # 100
math_func02 = get_math_func('cube')
print(math_func02(10))                              # 1000
math_func03 = get_math_func('add')
print(math_func03(10))                              # 20 
# 調(diào)用的方式和其他的都是一樣的 
向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI