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
Release: 2024-11-08 16:27:02
Original
870 people have browsed it

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)
Copy after login

This will result in the following output:

Wahaha!
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template