How to override `__str__` method in python
__str__ needs to be rewrite to provide a readable string representation of the object. 1. By default, class instances are printed as memory addresses, which are not intuitive; 2. Define the __str__ method when rewriting and return the formatted string; 3. Note that __str__ is for users and __repr__ is for developers; 4. The output format can be flexibly adjusted, such as dynamic splicing attribute values. For example, after rewriting the Person class, it can output meaningful information such as Person (name=Alice, age=30) or Alice is 30 years old.
In Python, __str__
is a special class method that defines an "informal" or readable friendly string representation of an object. Python will automatically call this method when you use print()
or str()
function to act on an object. If you want to make the instance of a custom class output clearer and meaningful information, you need to override it.

Here are some key points and suggestions on how to correctly override the __str__
method in your own class.

Why do you need to __str__
By default, if you do not override __str__
, you will only see information like <__main__.myclass object at></__main__.myclass>
when printing an instance of a class. This may be a little helpful for debugging, but not intuitive enough.
For example:
Suppose you have a Person
class that creates an instance p = Person("Alice", 30)
. You want print(p)
to output information similar to Person(name=Alice, age=30)
instead of a string of memory addresses.

That's why you need to rewrite __str__
- make your class output more meaningful strings.
How to correctly rewrite __str__
Define the __str__
method in your class and return a string. This is the basic structure:
class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f"Person(name={self.name}, age={self.age})"
This way, when you execute:
p = Person("Alice", 30) print(p)
It will output:
Person(name=Alice, age=30)
A few things to note:
-
__str__
must return a string type. - It only accepts
self
as an argument. - Don't confuse
__str__
and__repr__
, which are more detailed string representations for developers.
The difference from __repr__
Although both can control the string representation of an object, their uses are different:
-
__str__
: It is user-oriented and emphasizes readability. -
__repr__
: For developers, it is usually used for debugging and requires accurate restoration of objects.
For example, you can define __repr__
like this:
def __repr__(self): return f"Person('{self.name}', {self.age})"
This way, when entering variable names in an interactive environment, clearer results will also be displayed.
Tips in practical applications
Sometimes you may want to adjust the output format according to different needs. for example:
- Only output name and age, no prefix
"Person"
is required; - Format the output according to some fixed template;
- Make a judgment based on whether the attribute exists to avoid errors.
Let's give a simple example:
def __str__(self): return f"{self.name} is {self.age} years old."
Or, you want to make sure that some fields must exist before outputting:
def __str__(self): parts = [] if hasattr(self, 'name'): parts.append(f"name={self.name}") if hasattr(self, 'age'): parts.append(f"age={self.age}") return "Person(" ", ".join(parts) ")"
In this way, even if a certain attribute is missing, there will be no error.
Basically that's it. Although rewriting __str__
seems simple, if it can be used reasonably in actual projects, it will make debugging and log output more friendly.
The above is the detailed content of How to override `__str__` method in python. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Use httpx.AsyncClient to efficiently initiate asynchronous HTTP requests. 1. Basic GET requests manage clients through asyncwith and use awaitclient.get to initiate non-blocking requests; 2. Combining asyncio.gather to combine with asyncio.gather can significantly improve performance, and the total time is equal to the slowest request; 3. Support custom headers, authentication, base_url and timeout settings; 4. Can send POST requests and carry JSON data; 5. Pay attention to avoid mixing synchronous asynchronous code. Proxy support needs to pay attention to back-end compatibility, which is suitable for crawlers or API aggregation and other scenarios.

Install pyodbc: Use the pipinstallpyodbc command to install the library; 2. Connect SQLServer: Use the connection string containing DRIVER, SERVER, DATABASE, UID/PWD or Trusted_Connection through the pyodbc.connect() method, and support SQL authentication or Windows authentication respectively; 3. Check the installed driver: Run pyodbc.drivers() and filter the driver name containing 'SQLServer' to ensure that the correct driver name is used such as 'ODBCDriver17 for SQLServer'; 4. Key parameters of the connection string

This article aims to help SQLAlchemy beginners resolve the "RemovedIn20Warning" warning encountered when using create_engine and the subsequent "ResourceClosedError" connection closing error. The article will explain the cause of this warning in detail and provide specific steps and code examples to eliminate the warning and fix connection issues to ensure that you can query and operate the database smoothly.

shutil.rmtree() is a function in Python that recursively deletes the entire directory tree. It can delete specified folders and all contents. 1. Basic usage: Use shutil.rmtree(path) to delete the directory, and you need to handle FileNotFoundError, PermissionError and other exceptions. 2. Practical application: You can clear folders containing subdirectories and files in one click, such as temporary data or cached directories. 3. Notes: The deletion operation is not restored; FileNotFoundError is thrown when the path does not exist; it may fail due to permissions or file occupation. 4. Optional parameters: Errors can be ignored by ignore_errors=True

Python is an efficient tool to implement ETL processes. 1. Data extraction: Data can be extracted from databases, APIs, files and other sources through pandas, sqlalchemy, requests and other libraries; 2. Data conversion: Use pandas for cleaning, type conversion, association, aggregation and other operations to ensure data quality and optimize performance; 3. Data loading: Use pandas' to_sql method or cloud platform SDK to write data to the target system, pay attention to writing methods and batch processing; 4. Tool recommendations: Airflow, Dagster, Prefect are used for process scheduling and management, combining log alarms and virtual environments to improve stability and maintainability.

Install the corresponding database driver; 2. Use connect() to connect to the database; 3. Create a cursor object; 4. Use execute() or executemany() to execute SQL and use parameterized query to prevent injection; 5. Use fetchall(), etc. to obtain results; 6. Commit() is required after modification; 7. Finally, close the connection or use a context manager to automatically handle it; the complete process ensures that SQL operations are safe and efficient.

The method of filling Excel data into web forms using Python is: first use pandas to read Excel data, and then use Selenium to control the browser to automatically fill and submit the form; the specific steps include installing pandas, openpyxl and Selenium libraries, downloading the corresponding browser driver, using pandas to read Name, Email, Phone and other fields in the data.xlsx file, launching the browser through Selenium to open the target web page, locate the form elements and fill in the data line by line, using WebDriverWait to process dynamic loading content, add exception processing and delay to ensure stability, and finally submit the form and process all data lines in a loop.

Using PandasStyling in JupyterNotebook can achieve the beautiful display of DataFrame. 1. Use highlight_max and highlight_min to highlight the maximum value (green) and minimum value (red) of each column; 2. Add gradient background color (such as Blues or Reds) to the numeric column through background_gradient to visually display the data size; 3. Custom function color_score combined with applymap to set text colors for different fractional intervals (≥90 green, 80~89 orange, 60~79 red,
