全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-19 6 分钟 ✍️ juanwangdev

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() 检查对象是否可调用

📝 发现内容有误?点击此处直接编辑

← 上一篇 Python 偏函数 partial
下一篇 → Python 函数装饰器原理
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库