zoukankan      html  css  js  c++  java
  • 函数,匿名函数和内置函数

    函数

    定义函数的三种行式

    def func():
    	pass # 空函数
    
    def func():
    	print("hello python") # 无参函数
    
    def func(a):
    	print(f"{a}") # 有参函数
    

    函数返回值

    return 特性:

    • 用return返回值
    • 默认返回None
    • 没有return默认返回None
    • return代表函数执行终止,不再执行函数内return后面的代码
    • return可返回任意类型的值
    • return可返回多个值,用逗号隔开,返回的值是元组形式

    函数的参数

    形参

    • 位置形参
    def func(a, b, c):
    	pass
    
    • 默认形参
    def func(a, b, c=88):
    	pass
    
    • 不定长形参和关键字形参
    def func(a, *b, c=88):
    	pass # 当要为c传输参数时,必须用关键字实参传入
    	     # b为不定长形参
    
    def func(a, *, c=88):
    	pass # 当要为c传输参数时,必须用关键字实参传入
    

    实参

    • 位置实参
    def func(a, b, c):
    	pass
    func(1, 2, 3)
    
    • 关键字实参
    def func(a, b, c):
    	pass
    func(1, c = 2, b = 3) # 关键字实参必须在位置实参后面传入
    
    • 不定长实参
    def func(a, *b, c):
    	pass
    func(1, "b1", "b2", "b3", c = 3) # b1, b2, b3 都会传给b
    func(1, *["b1", "b2", "b3"], c = 3) # b1, b2, b3 都会传给b
    
    def func(a, *b, **c):
    	pass
    
    func(a, b1, b2, b3, c1=1, c2=2, c3=3) # 用b接受多余的实参(b的形式是元组),用c接收多余的关键字实参(c的接收形式是字典)
    func(a, *[b, b2, b3], **{c1:1, c2:2, c3:3}) # 也可用*或**打开列表或字典传入参数
    

    函数对象

    在python中一切皆对象,函数作为对象,可以在一下情况中使用:

    • 引用 a= func
    • 作为函数的参数 func1(func)
    • 作为函数的返回值
    • 作为容器内的元素 [func1, func2, func3]

    名称空间和作用域

    1. 内置名称空间: 存储了内置方法的名称
    2. 局部名称空间: 存储了函数运行过程中的变量,只在函数运行过程中存在
    3. 全局名称空间: 除了内置和局部的名称空间
    • 程序启动时产生内置名称空间
    • 运行时产生全局名称空间
    • 函数调用时产生局部名称空间

    查找顺序: LEGB: local, enclosed(外层函数的局部名称空间), global, builtin

    全局作用域:内置名称空间和全局名称空间

    匿名函数

    使用关键字lambda定义
    常与max, sorted, filter方法连用

    内置函数

    bytes:编码字符
    In [9]: "test".encode('utf8')
    Out[9]: b'test'
    
    chr/ord: 字符和Unicode编码的转换
    
    divmod: 取整和取余
    
    enumberate: 带有索引的迭代
    
    In [19]: hash("abc") # 返回对象的hash值
    Out[19]: -3367553503465544155
    
    dir: 返回对象的属性
    
    locals/globals: 查看局部和全局变量
    __import__: 通过字符串导入模块
    

    global 和nonlocal

    global 关键字让在函数内部定义的变量成为全局的
    nonlocal 关键字让其成为上层函数的局部
    
  • 相关阅读:
    Python学习札记(十五) 高级特性1 切片
    LeetCode Longest Substring Without Repeating Characters
    Python学习札记(十四) Function4 递归函数 & Hanoi Tower
    single number和变体
    tusen 刷题
    实验室网站
    leetcode 76. Minimum Window Substring
    leetcode 4. Median of Two Sorted Arrays
    leetcode 200. Number of Islands 、694 Number of Distinct Islands 、695. Max Area of Island 、130. Surrounded Regions 、434. Number of Islands II(lintcode) 并查集 、178. Graph Valid Tree(lintcode)
    刷题注意事项
  • 原文地址:https://www.cnblogs.com/YajunRan/p/11552755.html
Copyright © 2011-2022 走看看