Python 函数作为对象
函数是 Python 的一等公民,可像其他对象一样操作。
函数赋值
Python
def greet(name):
return f"Hello, {name}"
# 函数赋值给变量
say_hello = greet
print(say_hello("Alice")) # Hello, Alice
# 函数名只是指向函数对象的引用
print(greet) # <function greet at ...>
print(say_hello) # <function greet at ...>(同一个对象)
函数作为参数
Python
def apply(func, value):
return func(value)
def square(x):
return x ** 2
def double(x):
return x * 2
print(apply(square, 5)) # 25
print(apply(double, 5)) # 10
函数作为返回值
Python
def get_operation(name):
def add(a, b):
return a + b
def multiply(a, b):
return a * b
if name == 'add':
return add
elif name == 'multiply':
return multiply
operation = get_operation('add')
print(operation(3, 5)) # 8
函数存储在容器中
Python
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
# 存储在列表
operations = [add, subtract, multiply]
for op in operations:
print(op(10, 5))
# 输出: 15, 5, 50
# 存储在字典
ops_dict = {
'+': add,
'-': subtract,
'*': multiply
}
print(ops_dict['+'](3, 5)) # 8
函数属性
Python
def example():
"这是一个示例函数"
pass
# 函数内置属性
print(example.__name__) # example
print(example.__doc__) # 这是一个示例函数
print(example.__module__) # __main__
print(example.__code__) # 代码对象
# 自定义属性
example.version = '1.0'
example.author = 'Alice'
print(example.version) # 1.0
函数可调用检查
Python
def func():
pass
class MyClass:
def __call__(self):
return "可调用实例"
print(callable(func)) # True
print(callable(MyClass)) # True(类可调用)
print(callable(MyClass())) # True(实例实现了 __call__)
print(callable("string")) # False
函数与类对比
Python
# 函数
def create_counter():
count = 0
def inc():
nonlocal count
count += 1
return count
return inc
counter = create_counter()
print(counter()) # 1
# 类
class Counter:
def __init__(self):
self.count = 0
def inc(self):
self.count += 1
return self.count
c = Counter()
print(c.inc()) # 1
一等公民特性
| 特性 | 说明 | 示例 |
|---|---|---|
| 可赋值 | 赋给变量 | f = func |
| 可传递 | 作为参数 | apply(func, x) |
| 可返回 | 作为返回值 | return func |
| 可存储 | 存入容器 | [func1, func2] |
| 有属性 | 可添加属性 | func.version = '1.0' |
要点总结
- 函数是一等公民,与普通对象地位相同
- 函数名是引用,可赋值给其他变量
- 函数可作为参数传递和返回值返回
- 函数可存储在列表、字典等容器中
- 函数有内置属性如
__name__、__doc__ - 可自定义函数属性存储元数据
callable()检查对象是否可调用
📝 发现内容有误?点击此处直接编辑