arj*_*kok 11 python metaprogramming
>>> def hehe():
... return "spam"
...
>>> repr(hehe)
'<function hehe at 0x7fe5624e29b0>'
Run Code Online (Sandbox Code Playgroud)
我希望有:
>>> repr(hehe)
'hehe function created by awesome programmer'
Run Code Online (Sandbox Code Playgroud)
我怎么做?把__repr__内部hehe功能不起作用.
编辑:
如果你们想知道我为什么要这样做:
>>> defaultdict(hehe)
defaultdict(<function hehe at 0x7f0e0e252280>, {})
Run Code Online (Sandbox Code Playgroud)
我只是不喜欢它在这里显示的方式.
Mar*_*ers 10
不,您无法更改函数对象的表示形式; 如果你想添加文档,你需要添加一个文档字符串:
def foo():
"""Frob the bar baz"""
Run Code Online (Sandbox Code Playgroud)
并访问与help(foo)或print foo.__doc__.
您可以使用自定义创建可调用对象,该自定义__repr__就像一个函数:
class MyCallable(object):
def __call__(self):
return "spam"
def __repr__(self):
return 'hehe function created by awesome programmer'
Run Code Online (Sandbox Code Playgroud)
演示:
>>> class MyCallable(object):
... def __call__(self):
... return "spam"
... def __repr__(self):
... return 'hehe function created by awesome programmer'
...
>>> hehe = MyCallable()
>>> hehe
hehe function created by awesome programmer
>>> hehe()
'spam'
Run Code Online (Sandbox Code Playgroud)
通常,当您想要更改有关函数的内容时,比如函数签名,函数行为或函数属性,您应该考虑使用装饰器.所以这是你如何实现你想要的:
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 ...>
Run Code Online (Sandbox Code Playgroud)
请注意,您只能使用基于类的装饰器,因为您需要覆盖__repr__方法,而不能使用函数对象.
| 归档时间: |
|
| 查看次数: |
582 次 |
| 最近记录: |