Home >Backend Development >Python Tutorial >How to Customize the String Representation of a Python Class?

How to Customize the String Representation of a Python Class?

Linda Hamilton
Linda HamiltonOriginal
2024-11-08 16:27:02872browse

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 "". This might not always be desirable, especially when you want a custom string representation.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn