在 Python 2.7 中,如何覆盖单个函数的字符串表示形式?

2023-12-11

如何覆盖 Python 中单个函数的字符串表示形式?

我尝试过的:

>>> def f(): pass
... 
>>> f
<function f at 0x7f7459227758>
>>> f.__str__ = lambda self: 'qwerty'
>>> f
<function f at 0x7f7459227758>
>>> f.__repr__ = lambda self: 'asdfgh'
>>> f 
<function f at 0x7f7459227758>
>>> f.__str__(f)
'qwerty'
>>> f.__repr__(f)
'asdfgh'

我知道我可以通过上课来获得预期的行为__call__(使其看起来像一个函数)和__str__(自定义字符串表示形式)。不过,我很好奇是否可以通过常规函数得到类似的东西。


你不能。__str__ and __repr__是特殊方法,因此是总是寻找类型,不是实例。你必须重写type(f).__repr__在这里,但这适用于all功能。

那么你唯一现实的选择就是使用带有__call__ method:

def FunctionWrapper(object):
    def __init__(self, callable):
        self._callable = callable
    def __call__(self, *args, **kwargs):
        return self._callable(*args, **kwargs)
    def __repr__(self):
        return '<custom representation for {}>'.format(self._callable.__name__)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Python 2.7 中,如何覆盖单个函数的字符串表示形式? 的相关文章

随机推荐