Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a __str__ method for a class?

Tags:

python

In Python, the object class serves as the root superclass for all the (new-style) classes. By default at least, applying str and repr to the "class instance" of any subclass of object produces the same result:

>>> class spam(object): pass ...  >>> str(spam) "<class '__main__.spam'>" >>> str(spam) == repr(spam) 

I would like to define a subclass of object, say fancyobject, that is identical to object in every way, except that applying str and repr to fancyobject itself produces different outputs:

>>> class ham(fancyobject): pass ... >>> str(ham) 'ham' >>> repr(ham) "<class '__main__.ham'>" 

Is there a way to do this in Python?

PS: I'm aware of the __str__ special method, but it is my understanding that if class A overrides __str__, then the overriding method is called only when str is called on instances of A, not when it is called on A itself. I.e.:

>>> class A(object): ...     def __str__(self): ...         return 'from new __str__: ' + object.__str__(self) ...  >>> str(A()) 'from new __str__: <__main__.A object at 0x7f79c62a5310>' >>> str(A) "<class '__main__.A'>" 
like image 712
kjo Avatar asked Nov 15 '11 22:11

kjo


People also ask

How do you call the _ __ str __ method?

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.

What is the purpose of defining the functions __ str __ and __ repr __ within a class how are the two functions different?

__str__ is used in to show a string representation of your object to be read easily by others. __repr__ is used to show a string representation of the object.

What is an __ init __ method in a class?

The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approach. The __init__ function is called every time an object is created from a class. The __init__ method lets the class initialize the object's attributes and serves no other purpose. It is only used within classes.


2 Answers

Actually the same mechanism as for object instances applies for types. Types are just objects themselves, so they are converted to strings by calling the __str__() method on their type, which is called the "metaclass". So you have to overwrite the __str__() method on the metaclass:

class fancytype(type):     def __str__(self):         return self.__name__ class ham(object):     __metaclass__ = fancytype print ham 

prints

ham 
like image 107
Sven Marnach Avatar answered Oct 01 '22 08:10

Sven Marnach


You can also set the default metaclass for a whole module like this

class fancytype(type):     def __str__(self):         return self.__name__  __metaclass__ = fancytype  class ham:     pass print ham 
like image 22
John La Rooy Avatar answered Oct 01 '22 09:10

John La Rooy