You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中轻松修改str(function)的输出内容?

如何自定义Python函数的str()输出

默认情况下,直接打印用def定义的函数会返回类似<function myfunc_addition at 0x00000215FC2BC8C8>的冗长字符串,如果你想修改这个输出,又不想用类实例的方式,可以试试以下两种方法:

方法一:动态给函数绑定自定义__str__方法

利用Python的动态特性,给函数对象添加自定义的__str__方法,需要借助types.MethodType将方法绑定到函数实例上:

import types

def set_func_str(str_repr):
    def decorator(func):
        def __str__(self):
            return str_repr
        # 将自定义__str__绑定到函数实例
        func.__str__ = types.MethodType(__str__, func)
        return func
    return decorator

# 使用装饰器
@set_func_str(str_repr='+')
def myfunc_addition(a, b):
    return a + b

print(myfunc_addition(1, 2))  # 输出:3
print(str(myfunc_addition))   # 输出:+

方法二:用装饰器类包装函数

创建一个装饰器类,包装目标函数后返回带有自定义__str__的可调用对象,这种方式更灵活,还能扩展其他功能:

class CustomFuncRepr:
    def __init__(self, str_repr):
        self.str_repr = str_repr
    
    def __call__(self, func):
        self.func = func
        
        def wrapper(*args, **kwargs):
            return self.func(*args, **kwargs)
        
        # 给包装函数添加自定义__str__
        wrapper.__str__ = lambda _: self.str_repr
        return wrapper

# 使用装饰器类
@CustomFuncRepr(str_repr='+')
def myfunc_addition(a, b):
    return a + b

print(myfunc_addition(1, 2))  # 输出:3
print(str(myfunc_addition))   # 输出:+

原理说明

Python中用def定义的函数是function类的实例,它默认的__str__方法会返回包含内存地址的冗长字符串。我们通过动态绑定自定义__str__方法,或者用装饰器包装函数并替换其__str__实现,就能修改str(func)的输出结果。

内容的提问来源于stack exchange,提问作者dixhom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 22:30:33