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

标签 python python-2.7

如何在 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____repr__ 是特殊方法,因此是 always looked up on the type ,不是实例。您必须在此处覆盖 type(f).__repr__,但这将适用于所有 函数。

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

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 - 在 Python 2.7 中,如何覆盖单个函数的字符串表示形式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32156993/

相关文章:

python - 在 NLTK 中使用 block 标签(而非 NER)在句子中创建关系 |自然语言处理

python-2.7 - pygame 仅在鼠标在游戏窗口上处于事件状态时更新?

css - 使用 XPATH 的 Selenium Webdriver Python 从 html 表的第 1 列找到文本,我如何转到第 3 列

python - 梯度下降算法需要很长时间才能完成 - 效率 - Python

python - 使用 scrapy 从药物报告表中抓取数据

python - 提交后保持对数据库对象的锁定

python - 将数字应用于字符串的序列生成

python - 权限被拒绝 : Writing to CSV from Python

python - 在 python 中动态声明/创建列表

python:压缩csv缓冲区