"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Customize the String Representation of a Class in Python?

How Can I Customize the String Representation of a Class in Python?

Published on 2024-11-11
Browse:229

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 . Designing custom representation for classes can be useful for debugging, logging, or other purposes.

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!'
Latest tutorial More>

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