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!'
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3