简体   繁体   中英

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. 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 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM