当前位置: 首页 > news >正文

DAY11 函数对象 函数的嵌套 名称空间和作用域 作用域修改关键字

Python函数对象、嵌套和作用域总结

函数对象

函数在Python中是第一类对象,可以像普通变量一样使用。

1. 赋值给变量

def greet(name):
return f"Hello, {name}!"say_hello = greet# 将函数赋值给变量
print(say_hello("Alice"))# 输出: Hello, Alice!

2. 作为容器元素

def add(a, b):
return a + bdef subtract(a, b):
return a - boperations = [add, subtract]
print(operations[0](5, 3))# 输出: 8
print(operations[1](5, 3))# 输出: 2

3. 作为函数参数

def apply(func, x, y):
return func(x, y)def multiply(a, b):
return a * bprint(apply(multiply, 4, 5))# 输出: 20

4. 作为函数返回值

def create_power_function(exponent):
def power(base):
return base ** exponent
return powersquare = create_power_function(2)
cube = create_power_function(3)
print(square(4))# 输出: 16
print(cube(4))# 输出: 64

函数嵌套

def outer():
x = 10def inner():
print(f"x is {x}")# 内部函数可以访问外部函数的变量inner()# 在外部函数中调用内部函数outer()# 输出: x is 10
# inner()# 这会报错,外部无法直接访问内部函数

名称空间和作用域

1. 名称空间示例

# 全局名称空间
global_var = "I'm global"def my_function():
# 局部名称空间
local_var = "I'm local"
print(local_var)
print(global_var)# 可以访问全局变量my_function()
# print(local_var)# 这会报错,无法访问局部变量

2. 查找顺序示例

def test():
# len = "local len"# 如果取消注释,会覆盖内置len
print(len("hello"))# 查找顺序: 局部 -> 全局 -> 内置test()# 输出: 5

3. global关键字

count = 0def increment():
global count# 声明使用全局变量
count += 1increment()
print(count)# 输出: 1

4. nonlocal关键字

def outer():
x = "outer"def inner():
nonlocal x# 声明使用外层函数的变量
x = "inner"
print("Inner:", x)inner()
print("Outer:", x)outer()
# 输出:
# Inner: inner
# Outer: inner

5. 修改内置名称空间

# 修改全局名称空间中的内置函数
original_len = len# 保存原始len函数def my_len(obj):
return original_len(obj) * 2len = my_len# 覆盖内置len函数print(len("hi"))# 输出: 4 (原始长度2 * 2)
http://www.sczhlp.com/news/8236/

相关文章:

  • Python入门学习(九)Python的高级语法与用法(一)枚举
  • 进程间通信
  • GAS_Aura-Aura Player Controller
  • LP-BT100蓝牙耳机
  • OpenTelemetry概述
  • cocos2dx项目中遇到的spine问题
  • LGP11364 [NOIP 2024] 树上查询 学习笔记
  • 严格WQS二分
  • 2025 暑期 mx 集训 7.21
  • 8月8号
  • GPT-5 API 请求参数调整,避坑指南(汇总)
  • 题解:CF2048F Kevin and Math Class
  • gem5流程学习-1
  • SPI详细讲解+W25Q128验证
  • 【自学嵌入式:stm32单片机】蜂鸣器
  • 带 PVC 的 Pod 提交后时序事件
  • C#自学笔记:匿名函数与Lambda表达式
  • 如何高效率使用 Cursor ?
  • 注意力头
  • 8月8日
  • 一键上云不是梦!Apache Dubbo 发布微服务集群部署与全新控制台
  • 安装libretranslate
  • 解决 Vue 路由在 IIS 中的 404 问题
  • 位置嵌入
  • threejs之灯光不跟随OrbitControls控制器旋转
  • MAC在Docker上部署Ollama详细教程
  • 8月8日随笔
  • 场景题——高并发
  • 权重衰减系数
  • Burp Suite 拦截和修改 HTTP 接口请求