[英]How to set the output of `print(f)` for a function f
對於 Python 中的各種功能,如果我運行print(f)
,它會吐出一些東西。 例如,
print(print)
吐出來
<built-in function print>
現在當我定義
def f(x):
return x
print(f)
這吐出來
<function f at 0x7f3800fe8dd0>
有沒有辦法控制它吐出的東西? 我想放入我自己的自定義字符串,但我不知道該怎么做。 我知道如何為類做到這一點,但我很難找到一種方法來為函數做到這一點。
創建您自己的 class 實現__str__
和__call__
:
class Function:
def __init__(self, func, disp):
self.func = func
self.disp = disp
def __str__(self):
return self.disp
def __call__(self, *args, **kwds):
return self.func(*args, **kwds)
def f(x):
return x
# Pass the function as the first parameter, and the display string as the second
my_func = Function(f, 'my_func Function')
print(my_func)
print(my_func('abc'))
Output:
my_func Function
abc
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.