[英]How to set the output of `print(f)` for a function f
For various functions in Python, if I run print(f)
it will spit something out.对于 Python 中的各种功能,如果我运行
print(f)
,它会吐出一些东西。 For instance,例如,
print(print)
which spits out吐出来
<built-in function print>
Now when I define现在当我定义
def f(x):
return x
print(f)
This spits out这吐出来
<function f at 0x7f3800fe8dd0>
Is there a way to control what it spits out?有没有办法控制它吐出的东西? I'd like to put my own custom string in but I'm not sure how to do that.
我想放入我自己的自定义字符串,但我不知道该怎么做。 I know how to do that for classes, but I had trouble finding a way to do that for functions.
我知道如何为类做到这一点,但我很难找到一种方法来为函数做到这一点。
Create your own class which implements __str__
and __call__
:创建您自己的 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: Output:
my_func Function
abc
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.