[英]How do I change the representation while storing a sparse matrix in python?
[英]How do I change the representation of a Python function?
>>> def hehe():
... return "spam"
...
>>> repr(hehe)
'<function hehe at 0x7fe5624e29b0>'
我希望有:
>>> repr(hehe)
'hehe function created by awesome programmer'
我怎么做? 將__repr__
放在hehe
函數中是行不通的。
編輯:
如果你們想知道我為什么要這樣做:
>>> defaultdict(hehe)
defaultdict(<function hehe at 0x7f0e0e252280>, {})
我只是不喜歡它在這里顯示的方式。
不,您無法更改函數對象的表示形式; 如果你想添加文檔 ,你需要添加一個文檔字符串:
def foo():
"""Frob the bar baz"""
並使用help(foo)
或print foo.__doc__
訪問它。
您可以使用自定義__repr__
創建一個可調用對象,該函數就像一個函數:
class MyCallable(object):
def __call__(self):
return "spam"
def __repr__(self):
return 'hehe function created by awesome programmer'
演示:
>>> 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'
通常,當您想要更改有關函數的內容時,比如函數簽名,函數行為或函數屬性,您應該考慮使用裝飾器。 所以這是你如何實現你想要的:
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 ...>
請注意,您只能使用基於類的裝飾器,因為您需要覆蓋__repr__
方法,而您無法使用函數對象。
不直接回答你的問題,但也許你真的想要一個docstring?
>>> def hehe():
... '''hehe function created by awesome programmer'''
... return 'spam'
...
>>> help(hehe)
Help on function hehe in module __main__:
hehe()
hehe function created by awesome programmer
這是亞歷山大·朱可夫答案中的一個稍微靈活的版本:
def representation(repr_text):
class Decorator(object):
def __init__(self, functor):
self.functor = functor
def __call__(self, *args, **kwargs):
return self.functor(*args, **kwargs)
def __repr__(self):
return (repr_text % self.functor.__name__ if '%' in repr_text
else repr_text)
return Decorator
from collections import defaultdict
@representation('<function %s created by awesome programmer>')
def f():
return list
dd = defaultdict(f)
print repr(dd)
輸出:
defaultdict(<function f created by awesome programmer>, {})
由於representation()
返回一個裝飾器,如果你想在幾個函數上使用相同的樣板,你可以這樣做:
myrepr = representation('<function %s created by awesome programmer>')
@myrepr
def f():
...
@myrepr
def g():
...
etc
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.