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

class MyClass:
    def __init__(self, x, y):
        self.x = x
        self.y = y

obj = MyClass(1, 2)
print(vars(obj))

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

class MyClass:
    def __init__(self, x, y):
        self.x = x
        self.y = y

obj = MyClass(1, 2)

print(dir(obj))

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

class MyClass:
    def __init__(self, x, y):
        self.x = x
        self.y = y

obj = MyClass(1, 2)

print(obj.__dict__)

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__.