python子函数使用主函数变量

on under python
1 minute read

About

python中子函数使用主函数变量方法

Detail

子函数对主函数中的tmpvalue相当于复制,不是引用,下面子函数中只能读到主函数中的tmpvalue,不能修改主函数的tmpvalue

def mainfunc(folder, ext_list):
    tmpvalue=2 
    tmpvalueList = ["3"]

    def subfunc():
        print(tmpvalue)
        tmpvalue+=1
        print(tmpvalue)
        print(tmpvalueList)
        tmpvalueList[0]=("4")
        print(tmpvalueList)
    subfunc()
mainfunc(1,2)

------output------
Traceback (most recent call last):
  File "3.py", line 13, in <module>
    mainfunc(1,2)
  File "3.py", line 12, in mainfunc
    subfunc()
  File "3.py", line 6, in subfunc
    print(tmpvalue)
UnboundLocalError: local variable 'tmpvalue' referenced before assignment
------output------

但是子函数中可以对主函数中的数组写,比变量功能强大,子函数可以改变主函数中的tmpvalueList

def mainfunc(folder, ext_list):
    tmpvalue=2 
    tmpvalueList = ["3"]

    def subfunc():
        print(tmpvalue)
        #tmpvalue+=1
        #print(tmpvalue)
        print(tmpvalueList)
        tmpvalueList[0]=("4")
        print(tmpvalueList)
    subfunc()
mainfunc(1,2)

-------output-------
2
['3']
['4']
-------output-------
python
home
github
archive
category