目录
函数
函数的定义
通过函数体整体缩进来定义函数
def 函数名():
函数内的代码
return 返回值
函数的使用
函数名()
function() #调用函数
函数参数
必备参数
#必备参数
def fun(score,sex):
print(score,sex)
fun(100,'男')
fun(sex = '男',score=102)
默认参数
#默认参数
def fun(score,sex='男'):
print(score)
fun(126)
不定长参数
可以在参数名之前加上*表示任意长度的参数,参数会被转化成list:
也可以指定任意长度的关键字参数,在参数前加上**表示接受一个dict:
#不定长参数
#传入的是元组
def fun(*args):
print(args)
fun()
fun(*(1,2,'a'))
#传入字典
def fun(**kwargs):
print(kwargs)
fun()
fun(**{'key':'value','help':'ask'})
内置函数
查询python所有内置函数
import builtins
print(dir(builtins))
如果觉得内置函数都挤在一行,看起来麻烦,那我们利用重定向将内置函数写入到文本文件里面
import builtins
import sys
out = sys.stdout
sys.stdout = open(r'内置函数.txt','w')
print(dir(builtins))
sys.stdout.close()
sys.stdout=out
查看内置函数.txt里面的内容如下:
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
好多啊,越多,说明python越强大,都不用自己去实现这些功能,下面简要介绍几个内置函数
直接看python3.7.8官方文档:https://docs.python.org/zh-cn/3.7/library/functions.html
匿名函数
匿名函数一般用于 map filter等需要函数做参数的内置函数,绝大多数情况下都是使用def来定义函数
定义
lambda 参数: 返回值
使用
fun1 = lambda x,y : x + y
print('fun1(2,3)=' , fun1(2,3))
fun2 = lambda x: x*2
print('fun2(4)=' , fun2(4) )
fun1(2,3)= 5
fun2(4)= 8
作用域
global_value = 12
def test():
print(global_value) #可以查看全局变量
#global_value+=1 无法修改全局变量
test();
global声明全局变量
global_value = 12
def test():
# 声明全局变量
global global_value
global_value += 1
print(global_value) #可以查看全局变量
test();
函数嵌套
global_value = 12
def test():
local = 10
# 声明全局变量
global global_value
global_value += 1
print(global_value) #可以查看全局变量
def fun():
#声明全局变量
global global_value
global_value+=1
fun()
test()
局部变量
def test():
local = 10
def fun():
print(local)
#local+=1 无法修改局部变量
fun()
test()
nonlocal声明局部变量
def test():
local = 10
def fun():
nonlocal local
local += 1
print(local)
fun()
test()
总结下:使用不同作用域的变量一定要声明局部nonlocal或者global才能在当前作用域下使用
global_value = 12
def test():
local = 10
#声明全局变量
global global_value
global_value+=1
print(global_value)
def fun():
#声明局部变量
nonlocal local
local+=1
print(local)
fun()
test();
13
11
回调函数
假设现有函数A和函数B 两个函数,如果函数A何时被调用取决于函数B内部的代码;则函数A被称为回调函数
def main():
callback()
def callback():
print("回调函数调用")
main()
闭包
闭包是函数里面嵌套函数,外层函数返回里层函数,这种情况称之为闭包,
Python支持函数式编程,我们可以在一个函数内部返回一个函数:
def test():
def nest():
print("这里是被嵌套的函数")
return nest #将被嵌套的函数的函数名返回出去
nest_name = test()#调用外层函数获取被嵌套的幻术
nest_name() #通过获取的函数名使用该函数