How do you implement __str__ for a function?

后端 未结 2 446
既然无缘
既然无缘 2021-01-01 10:17

Given a function foo:

def foo(x):
     pass

Printing its representation by invoking str or repr give

2条回答
  •  失恋的感觉
    2021-01-01 11:14

    If you find yourself wrapping functions, it's useful to look at functools.partial. It's primarily for binding arguments of course, but that's optional. It's also a class that wraps functions, removing the boilerplate of doing so from scratch.

    from functools import partial
    
    class foo(partial):
        def __str__(self):
            return "I'm foo!"
    
    @foo
    def foo():
        pass
    
    assert foo() is None
    assert str(foo) == "I'm foo!"
    

提交回复
热议问题