Home >Backend Development >Python Tutorial >How to Customize the String Representation of a Python Class?
How to Customize the String Representation of a Class
In Python, the default string representation of a class looks like "
Implementing __str__() or __repr__()
To customize the string representation, you can implement the __str__() or __repr__() method in the class's metaclass. The metaclass is a class whose instances are classes.
For example:
class MC(type): def __repr__(self): return 'Wahaha!' class C(object): __metaclass__ = MC print(C)
This will result in the following output:
Wahaha!
Choosing the Appropriate Method
Use __str__() if you want a readable stringification, while __repr__() is used for unambiguous representations.
Python 3 Version
For Python 3, the syntax is slightly different:
class MC(type): def __repr__(self): return 'Wahaha!' class C(object, metaclass=MC): pass print(C)
The above is the detailed content of How to Customize the String Representation of a Python Class?. For more information, please follow other related articles on the PHP Chinese website!