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.nonlocalspa

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

  

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核心技术与实战 》blog

相关文章
相关标签/搜索