发布于2019-08-08 12:13 阅读(594) 评论(0) 点赞(4) 收藏(3)
def name(param1, param2, ..., paramN): statements return/yield value # optional
例:
嵌套函数的作用
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。
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
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.pythonheidong.com/blog/article/14071/458213b76a2fe472e858/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!