Skip to content

List attributes of an object โ€‹

In Python, you can use the built-in function dir() to list the attributes of an object. Here's an example of how you can use it:

Using the built-in dir() function to list attributes of an object in Python

python
class MyClass:
    def __init__(self):
        self.x = 5
        self.y = 10

obj = MyClass()
print(dir(obj))

This would output:

attributes output

console
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'x', 'y']

Note that dir() also returns the built-in attributes of the object, in addition to the attributes that you defined in the class. If you only want to see the attributes that you defined, you can use vars() function.

Returns the built-in attributes of the object, in addition to the attributes that you defined in the class

python
print(vars(obj))

This would output:

next output

console
{'x': 5, 'y': 10}

Do you find this helpful?

Dual-run preview โ€” compare with live Symfony routes.