Home > Article > Backend Development > How Can I Customize the String Representation of a Class in Python?
Customizing Class String Representation
In Python, classes are objects and thus have their own string representation. By default, this representation is
To achieve this customization, a metaclass is employed. In Python, a metaclass is a class that creates other classes. By implementing the __str__ or __repr__ method in a metaclass, the string representation of the class can be customized.
The __str__ method provides a user-readable string representation, while __repr__ provides an unambiguous representation for development and debugging. Here's an example using __repr__:
class MC(type): def __repr__(self): return 'Wahaha!' class C(object): __metaclass__ = MC print(C) # Prints 'Wahaha!'
In Python 3, the __metaclass__ attribute is replaced with a metaclass keyword argument. Here's the Python 3 version of the example:
class MC(type): def __repr__(self): return 'Wahaha!' class C(object, metaclass=MC): pass print(C) # Prints 'Wahaha!'
The above is the detailed content of How Can I Customize the String Representation of a Class in Python?. For more information, please follow other related articles on the PHP Chinese website!