如何在 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/