Home > Article > Backend Development > How can I customize the string representation of Python classes using metaclasses?
Custom String Representation for Classes: A Pythonic Approach
In Python, defining your own string representation for classes can offer greater control over how the class is presented. Unlike the default representation that resembles
Consider the following class:
class foo(object): pass
By default, converting foo to a string yields:
>>> str(foo) "<class '__main__.foo'>"
To customize this representation, you can implement either __str__() or __repr__() within the class's metaclass. These magic methods are responsible for returning the readable and unambiguous string representations of the class, respectively.
The following example demonstrates how to implement a custom __repr__() in a metaclass:
class MC(type): def __repr__(self): return 'Wahaha!' class C(object): __metaclass__ = MC print(C)
This code will output "Wahaha!" when you print the class C.
If you desire a readable stringification, use __str__; for unambiguous representations, use __repr__. Python 3 requires you to specify the metaclass in the class definition itself, like so:
class MC(type): def __repr__(self): return 'Wahaha!' class C(object, metaclass=MC): pass print(C)
The above is the detailed content of How can I customize the string representation of Python classes using metaclasses?. For more information, please follow other related articles on the PHP Chinese website!