Home >Backend Development >Python Tutorial >Does Python Have a Built-in Function Like PHP's print_r for Objects?

Does Python Have a Built-in Function Like PHP's print_r for Objects?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-30 19:15:15426browse

Does Python Have a Built-in Function Like PHP's print_r for Objects?

Do Objects Have Built-in Print Functions?

When debugging scripts, it's often useful to view the state of an object. PHP provides the print_r function for this purpose. Is there a similar built-in function in Python?

Answer:

While Python does not have a direct equivalent to print_r, you can achieve a similar result by combining the vars() and pprint() functions.

  • vars(): This function returns a dictionary containing the current properties and values of an object.
  • pprint(): This function provides a pretty-printed representation of a data structure, making it easy to read.

Example:

To print the properties and values of your_object, you can use the following code:

from pprint import pprint
pprint(vars(your_object))

This will display a nicely formatted list of all the object's properties and their current values.

The above is the detailed content of Does Python Have a Built-in Function Like PHP's print_r for Objects?. 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