函式的巢狀定義

2022-07-21 13:24:19 字數 777 閱讀 1469

'''

# 函式的巢狀定義:在函式內部定義函式

# 誕生的理由:乙個函式想使用另乙個函式內部的變數,可以定義在其內部

def func():

a = 10

def fn():

print(a)

return fn

new_fn = func()

new_fn()

''''''

# global關鍵字: 統一區域性與全域性的變數名

a = 100

def fn1():

global a

a = 200 # 讓函式的區域性變數a與全域性變數a統一,兩者是乙個

print(a)

fn1()

print(a)

'''# nonlocal關鍵字:統一區域性與巢狀區域性的變數名

def fn2():

num = 666

def fn22():

nonlocal num

num = 888

fn22()

print(num)

fn2()

# 作用域:

len = 10

def fn3():

len = 100

def fn33():

len = 1000

print('1:', len)

fn33()

print('2:', len)

fn3()

print('3:', len)

Python 函式 定義,巢狀,引數

定義函式 使用def 函式名 def say hello print hello1 print hello2 print hello3 say hello 使用函式名呼叫函式,如果不呼叫則不會輸出結果 系統自動跳過函式 結果 hello1 hello2 hello3def sum num1 20 n...

自定義函式 巢狀

目錄 函式巢狀的優點 保證內部函式的隱私。內部函式只能被其外部函式呼叫和訪問,不會暴露到全域性變數。coding utf 8 連線資料庫優化 from sqlalchemy import create engine import configparser,os def connectdb def g...

類的巢狀定義

直接寫乙個例子了解一下類的巢狀定義 include using namespace std define r 10 class stack void push int dt intpop class inside int main 程式相當於建立了乙個棧,類中定義了進棧和出棧,巢狀類返回棧已經存入的...