W3docs

Is there a built-in function to print all the current properties and values of an object?

In Python, you can use the built-in function vars() to print the properties and values of an object.

In Python, you can use the built-in function vars() to print the properties and values of an object. vars() returns the __dict__ attribute of an object, which is a dictionary containing the object's attributes and their values.

Here's an example:

Print all the current properties and values of an object in Python

python— editable, runs on the server

This will output:


{'x': 1, 'y': 2}

You can also use the dir() function to get a list of an object's attributes, including methods and properties.

Print all the current properties and values of an object in Python using the dir function

python— editable, runs on the server

Additionally, you can access the __dict__ attribute directly to return the attribute dictionary of an object.

Print all the current properties and values of an object in Python using the dict attribute

python— editable, runs on the server

This will output a dictionary like this:


{'x': 1, 'y': 2}

The dir() function returns a list of all attributes and methods, which can be useful when you want to inspect the object's interface. Note that vars() and __dict__ are not available on objects that define __slots__.