如何更改 Python 函数的表示? [英] How do I change the representation of a Python function?
问题描述
我想要:
<预><代码>>>>代表(呵呵)'hehe 函数由很棒的程序员创建'我该怎么做?将 __repr__
放在 hehe
函数中不起作用.
如果你们想知道我为什么要这样做:
<预><代码>>>>默认字典(呵呵)defaultdict(我只是不喜欢它在这里显示的方式.
通常,当您想更改函数的某些内容时,例如函数签名、函数行为或函数属性,您应该考虑使用装饰器.因此,您可以通过以下方式实现您想要的:
class change_repr(object):def __init__(self, functor):self.functor = 函子# 让我们从原始函数中复制一些关键属性self.__name__ = functor.__name__self.__doc__ = functor.__doc__def __call__(self, *args, **kwargs):返回 self.functor(*args, **kwargs)def __repr__(self):return '<由 ...创建的函数 %s>'% self.functor.__name__@change_repr定义 f():返回垃圾邮件"打印 f() # 垃圾邮件print repr(f) # <function hehe created by ...>
请注意,您只能使用基于类的装饰器,因为您需要覆盖 __repr__
方法,而使用函数对象则无法做到这一点.
>>> def hehe():
... return "spam"
...
>>> repr(hehe)
'<function hehe at 0x7fe5624e29b0>'
I want to have:
>>> repr(hehe)
'hehe function created by awesome programmer'
How do I do that? Putting __repr__
inside hehe
function does not work.
EDIT:
In case you guys are wondering why I want to do this:
>>> defaultdict(hehe)
defaultdict(<function hehe at 0x7f0e0e252280>, {})
I just don't like the way it shows here.
Usually, when you want to change something about the function, say function signature, function behavior or function attributes, you should consider using a decorator. So here is how you might implement what you want:
class change_repr(object):
def __init__(self, functor):
self.functor = functor
# lets copy some key attributes from the original function
self.__name__ = functor.__name__
self.__doc__ = functor.__doc__
def __call__(self, *args, **kwargs):
return self.functor(*args, **kwargs)
def __repr__(self):
return '<function %s created by ...>' % self.functor.__name__
@change_repr
def f():
return 'spam'
print f() # spam
print repr(f) # <function hehe created by ...>
Note, that you can only use class based decorator, since you need to override __repr__
method, which you can't do with a function object.
这篇关于如何更改 Python 函数的表示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!