在职前端Leader学习/转行 AI Agent -DAY6

6 阅读11分钟

2026.7.15 09:40

学习路线

Python -> Python进阶 -> Python数据分析 -> LangChain -> 机器学习 -> 神经网络 -> NLP -> Coze -> Dify -> 大模型应用基础 -> 大模型微调 -> 多模态 -> vibeCoding

复习巩固总结

一、集合字典
1. 集合 {1,2,3}  set frozenset
- 增 add update
- 删 pop clear remove discord
- 方法 difference union difference_update issubset issuperset isdisjoint

2. 字典  {a:1,b:2}  dict
- 删 clear del pop
- 改 update
- 查 get
- 方法 keys values items len

二、类
1. 类方法 @classmethod
2. 静态方法 @staticmethond
3. 抽象类 @abstractmethod

三、其他
1. 三元: 真 if 条件 else 假
2. 匿名函数 lambda 参数: 返回表达式
3. map: map(处理函数, 原始对象)  # 返回迭代器对象
4. filter: filter(处理函数, 原始对象)  # 返回迭代器对象
5. sorted: sorted(原始对象, key=处理函数指向, reverse=True/False)
- max min 也有 key
6. reduce: reduce(处理函数, 原始对象, 初始值)
7. 推导式: [表达式 for 变量 in 可迭代对象 if 筛选条件]

2026.07.14 11:16

Python 学习

117. 常用内置函数

# 一、输入与输出
# print() ===> 输出指定内容
# 完整参数: print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
# 参数详解:
#   1. objects: 要输出的内容
#   2. sep: 分隔符
#   3. end: 结束符
#   4. file: 输出位置
#   5. flush: 是否立即刷新
from unittest import result

print(10, 20, 30, 40)  # 10 20 30 40
print(10, 20, 30, 40, sep='-')  # 10-20-30-40
print(10, 20, 30, 40, sep='-', end='!')  # 10-20-30-40!
f = open('a.txt', 'w', encoding='utf-8')  # 用 utf-8 格式 write 到 a.text
print(10, 20, 30, 40, sep='-', end='!', file=f)

print('加载中')
print('.')
print('.')
print('.')
print('.')
print('.')
print('完成! ')

print('加载中', end='')
print('.', end='')
print('.', end='')
print('.', end='')
print('.', end='')
print('.', end='')
print('完成! ', end='')

# cmd中展示有问题,因为有缓存
import time
print('加载中', end='')
print('.', end='')
time.sleep(1)
print('.', end='')
time.sleep(1)
print('.', end='')
time.sleep(1)
print('.', end='')
time.sleep(1)
print('.', end='')
time.sleep(1)
print('完成! ', end='')

import time
print('加载中', end='', flush=True)
print('.', end='', flush=True)
time.sleep(1)
print('.', end='', flush=True)
time.sleep(1)
print('.', end='', flush=True)
time.sleep(1)
print('.', end='', flush=True)
time.sleep(1)
print('.', end='', flush=True)
time.sleep(1)
print('完成! ', end='')

import time
# 第一种进度条
print('加载中', end='', flush=True)
for index in range(5):
    print('.', end='', flush=True)
    time.sleep(1)
print('完成! ', end='')

# 第二种进度条
for index in range(1, 101):
    # print(f'已加载{index}', end='', flush=True)
    print(f'\r已加载{index}', end='', flush=True)
    time.sleep(0.1)

# input() ===> 获取输入内容

# 二、类型转换
# int() ======> 转为整数
# float() ====> 转为浮点数
# str() ======> 转为字符串
# bool() =====> 转为布尔值
# list() =====> 转为列表
# tuple() ====> 转为元祖
# set() ======> 转为集合
# dict() =====> 转为字典

# 三、数学相关
# abs() =========> 取绝对值
print(abs(-9))  # 9
print(abs(-2.5))  # 2.5
print(abs(3 - 5))  # 2

# round() =======> 四舍五入
# 注意: round函数的四舍五入,是银行家舍入法: 小于5就舍,大于5就入,等于5看奇偶(奇入偶舍)
print(round(3.4))  # 3
print(round(4.6))  # 5
print(round(6.5))  # 6
print(round(7.5))  # 8
print(round(7.543, 2))  # 7.54

# pow() =========> 次方
print(pow(2, 3))      # 2的3次方 2 ^ 3 = 8
print(pow(2, -1))     # 2的-1次方 2 ^ -1 = 0.5
print(pow(2, 0.5))    # 2的开平方 2 ^ 0.5 = 1.4142135623730951
print(pow(2, 3, 5))   # 2的3次方对5取模  3

# divmod() ======> 商和余数
print(divmod(10, 3))  # 10 / 3 = 3 ... 1  (3, 1)

# max() =========> 最大值(支持 key 函数)
# min() =========> 最小值(支持 key 函数)
# sum() =========> 求和
# map() =========> 加工一组数据
# filter() ======> 按条件过滤数据(支持 key 函数)
# reduce() ======> 合并计算(需导入 functools)
# sorted() ======> 排序(支持 key 函数)

# 四、数据容器相关
# len() ==========> 获取容器中元素的个数
# range() ========> 生成一个数字序列(可用于循环)
for index in range(10):
    print(index)  # 0123456789

for index in range(0, 10):
    print(index)  # 0123456789

for index in range(0, 10, 1):
    print(index)  # 0123456789

for index in range(0, 10, 2):
    print(index)  # 02468

# enumerate() ====> 给序列添加索引
# zip() ==========> 将多个序列——配对
names = ('张三', '李四', '王五')
scores = [60, 70, 80]
result = zip(names, scores)
# print(result)  # 可迭代对象
# print(list(result))  # [('张三', 60), ('李四', 70), ('王五', 80)]
# print(tuple(result))  # (('张三', 60), ('李四', 70), ('王五', 80))
for item in result:
    print(item)  # ('张三', 60)  ('李四', 70)  ('王五', 80)

names = ('张三', '李四')
result = zip(names, scores)
for item in result:
    print(item)  # ('张三', 60)  ('李四', 70)

# 五、类型判断与对象相关
# type() ==========> 查看类型
# isinstance() ====> 判断类型
# issubclass() ====> 判断两个类的集成关系
# id() ============> 查看对象的内存地址

# 六、逻辑判断相关
# all() ====> 全为真返回True
l1 = [10, '尚硅谷', {1, 2, 3}, 0]
print(all(l1))  # False

l1 = [10, '尚硅谷', {1, 2, 3}, -9]
print(all(l1)) # True

# any() ====> 有一个为真即可
l2 = [0, '', None, False]
print(any(l2))  # False

l2 = [0, '', None, False, 10]
print(any(l2))  # True

# 七、字符串辅助相关
# ord() ====> 获取字符的 Unicode 编码值
# chr() ====> 将 Unicode 编码值转为字符

2026.07.14 13:09

118. 浅拷贝_深拷贝

# 直接赋值: 两个变量指向同一个对象,修改其中一个,就会影响另一个(互相影响)
nums1 = [10, 20, 30, 40]
nums2 = nums1
print(id(nums1))  # 地址1
print(id(nums2))  # 地址1
nums2[3] = 99
print(nums1[3])  # 99
print(nums2[3])  # 99

# 浅拷贝: 创建一个新的外层容器,但内部元素仍然引用原来的对象
nums1 = [10, 20, 30, 40]
import copy
nums2 = copy.copy(nums1)
print(id(nums1))  # 地址2
print(id(nums2))  # 地址3
nums2[3] = 99
print(nums1[3])  # 40
print(nums2[3])  # 99

# 浅拷贝存在的问题: 嵌套数据仍然是共享的,修改嵌套数据会互相影响
nums1 = [10, 20, 30, [40, 50]]
nums2 = copy.copy(nums1)
print(id(nums1))  # 地址4
print(id(nums2))  # 地址5
nums2[3][0] = 99
print(nums1[3][0])  # 99
print(nums2[3][0])  # 99

# 深拷贝: 创建一个新的外层容器,并对其内部所有的【可变子对象】进行递归复制
# 备注:
#   1. 深拷贝可以彻底消除数据之间的互相影响
#   2. 深拷贝遇到【不可变对象】不会复制,会直接引用
nums1 = [10, 20, 30, [40, 50]]
nums2 = copy.deepcopy(nums1)
print(id(nums1))  # 地址6
print(id(nums2))  # 地址7
print(id(nums1[3]))  # 地址8
print(id(nums2[3]))  # 地址9
nums2[3][0] = 99
print(nums1[3][0])  # 40
print(nums2[3][0])  # 99

# 注意点:
#   1. 深拷贝只复制可变对象,不可变对象会直接引用
a = 666
b = copy.deepcopy(a)
print(id(a))  # 地址10
print(id(b))  # 地址10

#   2. 元组中如果只包含不可变对象,则深拷贝没有效果
nums1 = (10, 20, 30, (40, 50))
nums2 = copy.deepcopy(nums1)
print(id(nums1))  # 地址11
print(id(nums2))  # 地址11

nums1 = (10, 20, 30, [40, 50])
nums2 = copy.deepcopy(nums1)
print(id(nums1))  # 地址12
print(id(nums2))  # 地址13

119. 四种作用域

  • Python 中有四种作用域,分别是:LocalEnclosingGlobalBuilt-in
  • 当访问一个变量时,Python 会按以下顺序查找:Local => Enclosing => Global => Built-in

1. 局部作用域(Local)

函数的内部就是局部作用域,局部作用域中的变量,只能在该函数内部可见。

  • 每次调用函数都会创建一个新的局部作用域
  • 函数运行结束后,局部作用域随之销毁
  • 局部作用域优先级最高(LEGB 中的 L)

举例:

def test():
    x = 10  # x 在局部作用域
    print(x)  # 可以访问

print(x)  # ❌ 报错:x 在局部之外不可见

2. 外层作用域 (Enclosing)

定义:如果函数中又定义了函数,那么外层函数的作用域,就是内层函数的 Enclosing 作用域。

特点

  • 只有当函数 “嵌套定义” 时才会出现
  • 内层函数可以读取外层函数变量
  • 想修改外层变量必须使用 nonlocal

举例:

def outer():
    y = 20  # outer 的局部变量 -> inner 的 Enclosing 变量

    def inner():
        print(y)  # 内层函数读取外层变量

    inner()

修改外层变量:

def outer():
    y = 20

    def inner():
        nonlocal y
        y = 99  # 修改外层函数作用域变量

3. 全局作用域 (Global)

定义.py 文件就是全局作用域,全局作用域中的变量,在当前 .py 文件的任何位置都可以访问。

特点

  • 全局变量只在当前 .py 文件中可见
  • 函数内部可以使用 global 关键字修改全局变量

例子:

a = 100  # 全局变量

def test():
    print(a)  # 可以读取

test()
print(a)  # 在本文件任何位置都可以访问

如果要修改:

a = 100

def test():
    global a
    a = 200  # 修改全局变量

4. 内建作用域 (Built-in)

定义:Python 预先定义好的东西,会放在内建作用域中,所有 .py 文件都可以直接使用。

特点

  • 所有 .py 文件都能直接使用其中的名称
  • 例如:printlenrangesummax
  • 查找优先级最低(LEGB 的 B)

例子:

print('hello')
len([1, 2, 3])

代码示例总结

a = 100
def test():
    global a
    a = 999
    print('我是test函数')
    print('test中打印的a是', a)  # 100 -> 999

print('全局打印的a是', a)  # 100
test()
print('全局打印的a是', a)  # 100 -> 999

a = 100
def test(b):
    print('我是test函数')
    print('test中打印的a是', a)  # 100
    print('test收到的参数b是', b)  # 66
    c = 200
    d = 200
    print('test中的c和d是', c, d)  # 200 300

print('全局打印的a是', a)  # 100
test(66)
# print(b, c, d)  # 报错
# print(c, d)  # 报错
# print(d)  # 报错

a = 100
def test(b):
    print('我是test函数')
    print('test中打印的a是', a)  # 100
    print('test收到的参数b是', b)  # 66
    c = 200
    d = 200
    print('test中的c和d是', c, d)  # 200 300
    def inner():
        e = 400
        nonlocal c
        c = 999
        print('inner中的e是', e)  # 400
        print('inner中打印的c是', c)  # 200 -> 999
        print('############', a)  # 100
    inner()
    print('**********', c)  # 200 -> 999

print('全局打印的a是', a)  # 100
test(66)

2026.07.15 16:57

119. 闭包

# 前置知识一:
# 1. 每次调用函数时,Python 都会为函数创建一个新的局部作用域
# 2. 函数执行完毕后,这个局部作用域会被销毁,其中的局部变量也会随之被释放
def outer():
    num = 10
    num += 1
    print(num)  # 11

outer()
outer()
outer()

# 前置知识二:
# 1. 在 Python 中,【内层函数】可以访问其【外层函数】作用域中的变量
# 2. 访问外层函数变量无需使用 nonlocal;但修改外层变量时要使用 nonlocal
def outer():
    num = 10

    def inner():
        nonlocal num
        num = 99
        print(1, num)  # 10 -> 99
    inner()
    print(2, num)  # 10 -> 99

outer()

# 闭包
def outer():
    num = 10
    # print(id(num))
    print(hex(id(num)))  # 地址1
    # msg = '尚硅谷'

    def inner():
        nonlocal num
        num += 1
        print(num)  # 10 -> 11
        # print(msg)

    print(id(inner))  # 地址1

    return inner

# outer()
f = outer()
print(id(f))  # 地址1
f()  # 10 -> 11
f()  # 12
f()  # 13

# 打印 __closure__ 元组
# print(inner.__closure__)
print(f.__closure__)  # 元组 有一个元素:闭包单元,地址1 -> 两个

# 结论
# 1. outer 函数中,被 inner 所使用到的那些变量,会被封存到【闭包单元(cell)】中
# 2. 这些 cell 会组成一个 __closure__ 元组,最终放在了 inner 函数身上

# 打印 __closure__ 元组中的某一项
print(f.__closure__[0])  # 闭包单元,地址1

# 打印 __closure__ 元组中的某一项
print(f.__closure__[0].cell_contents)  # 10

# 什么是闭包? —— 闭包 = 内层函数(inner) + 被内层函数所引用的外层变量(inner.__closre__)
# 闭包产生的条件:
#   1. 要有函数嵌套
#   2. 在【内层函数】中,要访问【外层函数】的变量
#   3. 并且【外层函数】要返回【内层函数】 —— 只有返回了内层函数,闭包才能“活下来”

def outer():
    num = 10
    def inner():
        nonlocal num
        num += 1
        print(num)
    print(inner.__closure__)  # 有数据
    # return inner
outer()

# 注意点:
# 1. 调用n次外层函数,就会得到n个不同的闭包,并且这些闭包之间互不影响
def outer():
    num = 10
    def inner():
        nonlocal num
        num += 1
        print(num)
    return inner
f1 = outer()
f1()  # 11
f1()  # 12
f1()  # 13
print('***********')
f2 = outer()
f2()  # 11

# 2. 内层函数中用到的外层变量是可变对象,多个闭包之间依然互不影响
def outer():
    nums = []
    def inner(value):
        # nonlocal nums
        nums.append(value)
        print(nums)
    return inner
f1 = outer()
f1(10)  # [10]
f1(20)  # [10, 20]
f1(30)  # [10, 20, 30]
print('***********')
f2 = outer()
f2(666)  # [666]

# 闭包的优点
# 1. 可以“记住”状态: 不用全局变量,也不用写类,就能在多次调用之间保存数据
# 2. 可以做“配置过的函数”: 先传一部分参数,把环境固定住,得到一个定制版函数
# 3. 可以实现简单的“数据隐藏”: 外层变量对外不可见,只能通过内层函数访问
# 4. 是装饰器(decorator)等高级用法的基础

def beauty(char, n):
    def show_msg(msg):
        print(char * n + msg + char * n)
    return show_msg
show1 = beauty('*', 3)
show1('你好啊')
show1('尚硅谷')
show2 = beauty('@', 5)
show2('你好啊')
show2('尚硅谷')

# 闭包的缺点:
# 1. 理解陈本较高: 对初学者不太友好,泛用会让代码难读
# 2. 如果闭包里引用了很大对象,又长期不释放,可能会增加内存占用
# 3. 很多场景下,其实用【类 + 实例属性】会更清晰,闭包不一定是最优解

class Beauty:
    def __init__(self, char, n):
        self.char = char
        self.n = n
    def show_msg(self, msg):
        print(self.char * self.n + msg + self.char * self.n)
b1 = Beauty('*', 3)
b1.show_msg('你好啊')
b1.show_msg('尚硅谷')
b2 = Beauty('#', 5)
b2.show_msg('你好啊')
b2.show_msg('尚硅谷')