2

I tried to overload the str and repr methods for a python function, like so:

def func():
  pass

func.__str__ = lambda: 'func_str'
func.__repr__ = lambda: 'func_repr'

Calling these methods directly produces the exepcted output:

print(func.__str__())#output: func_str
print(func.__repr__())#output: func_repr

But calling the str() and repr() methods on the func object directly seems to ignore the overloaded methods:

print(str(func)) # <function func at 0x0000023C148CC310>
print(repr(func)) # <function func at 0x0000023C148CC310>

Question: Why is str(func) not the same as func.__str__()? If this is not the intended way of giving a function a str() and repr(), what would be the best approach?

LcdDrm
  • 1,009
  • 7
  • 14
  • Please have a look [here](https://stackoverflow.com/questions/22797580/how-to-replace-str-for-a-function), this has been answered before. – python_ged May 04 '21 at 06:18
  • I don't see the reason for using `__str__` and `__repr__` methods for a function. People generally use them in classes for their objects to display some attribute information about themselves. Example: Imagine a class `Car` with attribute `model_name` or `registration_no`. You can then use the above methods to display them. – Kishore Sampath May 04 '21 at 06:22
  • str(a) calls type(a).__str__(a), therefore str(func) actually is type(func).__str__(func). – zuijiang May 04 '21 at 06:32
  • 1
    Essentially, setting special methods, i.e. "dunder" methods on instances is usually useless because they are looked up on the type directly as an optimization. This means you cannot modify dunder methods on a per-instance basis, or (sanely) monkey-patch built-in types – juanpa.arrivillaga May 04 '21 at 07:08

0 Answers0