Python3 函数及函数变量作用域

函数 是组织好的、可重复使用的、用来实现单一或相关联功能的代码段。

  • 函数代码块以def关键词开头,后接函数标识符名称和圆括号()
  • 任何传入参数和自变量必须放在圆括号中间。圆括号之间可以用于定义参数
  • 函数的第一行语句可以选择性地使用文档字符串——用于存放函数说明
  • 函数内容以冒号起始,并且缩进
  • return[expression]结束函数,选择性地返回一个值给调用方。不带表达式的return相当于返回 None
  • 若采用默认参数定义函数,调用函数时,缺省参数的值如果没有传入,则被认为是默认值
  • def test1(arg1='参数一', arg2='参数二'):
        print('arg1:'+arg1)
        print('arg2:'+arg2)
    
    test1()  # arg1:参数一  arg2:参数二
    
    # 默认情况下,参数值和参数名称是按函数声明中定义的的顺序匹配起来的
    test1('ice', 'cream')  # arg1:ice  arg2:cream
    test1(arg2='cream', arg1='ice')  # arg1:ice  arg2:cream
    实例
  • 不定长参数。加了星号(*)的变量名会存放所有未命名的变量参数。
  • def test2(*args, param):
        print(len(args))
        for arg in args:
            print(arg)
        print(param)
    
    test2(1, 2, 3, 4, param='This is param')
    
    
    def test3(param, *args):
        print(param)
        print(len(args))
        for arg in args:
            print(arg)
    
    test3('This is param', 1, 2, 3, 4)
    实例
  • 所有参数(自变量)在Python里都是按引用传递。如果在函数里修改了参数,那么在调用这个函数的函数里,原始的参数也被改变了
  • def test4(mylist):
        print(mylist)
        mylist.clear()
        print(mylist)
    
    mylist = [1, 2, 3, 4]
    test4(mylist)
    print(mylist)
    
    # 输出:
    # [1, 2, 3, 4]
    # []
    # []
    实例
  • return语句[表达式]退出函数,选择性地向调用方返回一个表达式。不带参数值的return语句返回None
  • def test5():
        return (1, 2, 3, 4)
    
    
    def test6():
        return 1, 2, 3, 4
    
    
    def test7():
        return [1, 2, 3, 4]
    
    result = test5()
    print(result)  # (1, 2, 3, 4)
    
    result = test6()
    print(result)  # (1, 2, 3, 4)
    
    result = test7()
    print(result)  # [1, 2, 3, 4]
    实例
  • 内部函数。函数体内可以再定义函数
  • def outerFunc():
        print('Outer Funtion')
        def innerFunc():
            print('Inner Function')
        innerFunc()
        
    outerFunc()
    
    # 输出:
    # Outer Funtion
    # Inner Function
    实例

函数的作用域  

定义在函数内部的变量拥有一个局部作用域,定义在函数外的拥有全局作用域。

局部变量只能在其被声明的函数内部访问,而全局变量可以在整个程序范围内访问。调用函数时,所有在函数内声明的变量名称都将被加入到作用域中

  • temp = 'ice cream'
    
    def test8():
        "全局变量可以在整个程序范围内访问"
        print(temp)
    
    
    def test9():
        inner_temp = 'ice'
        print(inner_temp)
    
    print(temp)  # ice cream
    test8()  # ice cream
    test9()  # ice
    
    
    # 局部变量只能在其被声明的函数内部访问
    print(inner_temp)  # 报错  name 'inner_temp' is not defined
    
    def test10():
        print(temp)  # 报错  local variable 'temp' referenced before assignment
        temp = 'ice'
        print(temp)
    实例

猜你喜欢

转载自www.cnblogs.com/dx-Dark/p/9056302.html