Created
January 22, 2023 14:30
-
-
Save anthonyraf/5dc69338e0cf7986483f300ec9eb60bb to your computer and use it in GitHub Desktop.
Overwrite python function __repr__ and __str__
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CustomFunction: | |
def __init__(self, func): | |
self.func = func | |
def __call__(self, *args, **kwargs): | |
return self.func(*args, **kwargs) | |
def __str__(self): | |
return "A custom function" | |
def __repr__(self): | |
return "<custom function>" | |
def my_function(name): | |
return f"Hello {name}!" | |
my_function = CustomFunction(my_function) # You can also use @CustomFunction decorator directly on the function declaration | |
print(my_function("John")) # => Hello John! | |
list_for_testing_repr = [my_function] | |
print(list_for_testing_repr) # => [<custom function>] | |
print(my_function) # => "A custom function" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment