Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace __str__ for a function

I want to change the string representation of a python function to be just the function name.

Eg for some function

def blah(x):
 ...

str(blah) currently gives

<function blah at 0x10127b578>

So I replace __str__ like this:

blah.__str__=lambda: 'blah'

but it doesn't get called by str(blah).

Is it possible to change __str__ for a function?

like image 979
macduff Avatar asked Apr 01 '14 21:04

macduff


People also ask

What is __ str __ function in Python?

Python __str__() This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object. This method must return the String object.

What is __ str __ called?

The __str__ method in Python represents the class objects as a string – it can be used for classes. The __str__ method should be defined in a way that is easy to read and outputs all the members of the class. This method is also used as a debugging tool when the members of a class need to be checked.

What is the difference between repr () or str () function?

repr() compute the “official” string representation of an object (a representation that has all information about the object) and str() is used to compute the “informal” string representation of an object (a representation that is useful for printing the object).

What is def __ str __( self?

def str(self): is a python method which is called when we use print/str to convert object into a string.


1 Answers

As noted already, the answer is no. If you just want to get the name of a function as a string, you can use blah.__name__.

like image 80
khagler Avatar answered Sep 22 '22 16:09

khagler