Python基础:自定义函数

函数的形式:

def name(param1, param2, ..., paramN):
    statements
    return/yield value # optional
  • 和其他需要编译的语言(比如 C 语言)不一样的是,def 是可执行语句,这意味着函数直到被调用前,都是不存在的。当程序调用函数时,def 语句才会创建一个新的函数对象,并赋予其名字。
  • Python 是 dynamically typed ,对函数参数来说,可以接受任何数据类型,这种行为在编程语言中称为多态。所以在函数里必要时要做类型检查,否则可能会出现例如字符串与整形相加出异常的情况。

函数的嵌套:

  例:

def f1():
    print('hello')
    def f2():
        print('world')
    f2()
f1()
'hello'
'world'

  嵌套函数的作用

  • 保证内部函数的隐私
def connect_DB():
    def get_DB_configuration():
        ...
        return host, username, password
    conn = connector.connect(get_DB_configuration())
    return conn

  在connect_DB函数外部,并不能直接访问内部函数get_DB_configuration,提高了程序的安全性

  • 如果在需要输入检查不是很快,还会耗费一定资源时,可以使用函数嵌套提高运行效率。
def factorial(input):
    # validation check
    if not isinstance(input, int):
        raise Exception('input must be an integer.')
    if input < 0:
        raise Exception('input must be greater or equal to 0' )
    ...

    def inner_factorial(input):
        if input <= 1:
            return 1
        return input * inner_factorial(input-1)
    return inner_factorial(input)
print(factorial(5))

函数作用域

  1.global

  在Python中,我们不能在函数内部随意改变全局变量的值,会报local variable 'VALUE' referenced before assignment。

  下例通过global声明,告诉解释器VALUE是全局变量,不是局部变量,也不是全新变量
VALUE = 10
LIST = ['a','b']
print(id(LIST)) #2490616668744
def validation_check(value):
    global VALUE
    VALUE += 3 #如果注释掉global VALUE,会报local variable 'VALUE' referenced before assignment
    
    LIST[0] = 10 #可变类型无需global可以使用全局变量?
    print(id(LIST)) #2490616668744
    print(f'in the function VALUE: {LIST}') #in the function VALUE: [10, 'b']
    print(f'in the function VALUE: {VALUE}') #in the function VALUE: 13

validation_check(1)
print(f'out of function {LIST}') #out of function [10, 'b']
print(f'out of function {VALUE}') #out of function 13
#a: 13
#b: 13

  2.nonlocal

  对于嵌套函数,nonlocal 声明变量是外部函数中的变量

  

def outer():
    x = "local"
    def inner():
        nonlocal x # nonlocal 关键字表示这里的 x 就是外部函数 outer 定义的变量 x
        x = 'nonlocal'
        print("inner:", x)
    inner()
    print("outer:", x)
outer()
# inner :nonlocal
# outer :nonlocal
  当内部变量与外部变量同名时,内部变量会覆盖外部变量
def outer():
    x = "local"
    def inner():
        x = 'nonlocal' # 这里的 x 是 inner 这个函数的局部变量
        print("inner:", x)
    inner()
    print("outer:", x)
outer()
# 输出
# inner: nonlocal
# outer: local

闭包

  • 内部函数返回一个函数
  • 外部函数nth_power()中的exponent参数在执行完nth_power()后仍然会被内部函数exponent_of记住
def nth_power(exponent):
    def exponent_of(base):
        return base ** exponent
    return exponent_of # 返回值是 exponent_of 函数

square = nth_power(2) # 计算一个数的平方
cube = nth_power(3) # 计算一个数的立方 
# square
# # 输出
# <function __main__.nth_power.<locals>.exponent(base)>

# cube
# # 输出
# <function __main__.nth_power.<locals>.exponent(base)>

# print(square(2))  # 计算 2 的平方
# print(cube(2)) # 计算 2 的立方
# # 输出
# 4 # 2^2
# 8 # 2^3

参考:

  极客时间《Python核心技术与实战 》

原文地址:https://www.cnblogs.com/xiaoguanqiu/p/10948995.html