在 Python 2.7 中,如何覆盖单个函数的字符串表示? [英] In Python 2.7, how do I override the string representation of a single function?

查看:43
本文介绍了在 Python 2.7 中,如何覆盖单个函数的字符串表示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我尝试过的:

<预><代码>>>>def f(): 通过...>>>F<函数 f 在 0x7f7459227758>>>>f.__str__ = lambda 自我:'qwerty'>>>F<函数 f 在 0x7f7459227758>>>>f.__repr__ = lambda 自我:'asdfgh'>>>F<函数 f 在 0x7f7459227758>>>>f.__str__(f)'qwerty'>>>f.__repr__(f)'asdfgh'

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

解决方案

你不能.__str____repr__ 是特殊方法,因此是 总是查找类型,而不是实例.您必须在此处覆盖 type(f).__repr__,但这将适用于所有函数.

你唯一现实的选择是使用带有 __call__ 方法的包装对象:

def FunctionWrapper(object):def __init__(self, callable):self._callable = 可调用def __call__(self, *args, **kwargs):返回 self._callable(*args, **kwargs)def __repr__(self):return '<custom representation for {}>'.format(self._callable.__name__)

How do I override the string representation for a single function in Python?

What I have tried:

>>> 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'

I know I can get the expected behavior by making a class with __call__ (to make it look like a function) and __str__ (to customize the string representation). Still, I'm curious if I can get something similar with regular functions.

解决方案

You can't. __str__ and __repr__ are special methods and thus are always looked up on the type, not the instance. You'd have to override type(f).__repr__ here, but that then would apply to all functions.

Your only realistic option then is to use a wrapper object with a __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__)

这篇关于在 Python 2.7 中,如何覆盖单个函数的字符串表示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆