Get a list of Class Attributes in Python

In Python, Object-Oriented Programming (OOP) is based on classes that are used to create new objects easily. This is where we will define the methods and attributes linked to an object. If we create a new class, called Human(), where we assign two attributes, age and height, we can easily their values using the print statement, as shown below:

class Human(): age = 30 height = 180 human = Human() print(human.age)
Code language: Python (python)

Output:

30

It can be easily to know what are the available attributes and methods that we can use on a specific object. In this tutorial, we’ll discover how we can achieve that.

Use the dir() function to find all the class attributes

If we read the official documentation, the dir() function achieve a simple thing: If the object has a method named __dir__(), this method will be called and must return the list of attributes.

class Human(): age = 30 height = 180 eye_color ='blue' print(dir(Human))
Code language: Python (python)

Output:

['__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__', 'age', 'eye_color', 'height']
Code language: JSON / JSON with Comments (json)

The list is longer than expected because the function returns also magic methods of our object. Please note that you can alter this behavior by creating a custom definition for __dir__ for your object and create an instance. When called, the function dir() will return what you indicated.

class Human(): age = 30 height = 180 eye_color ='blue' def __dir__(self): return ['It is secret!'] human = Human() print(dir(human))
Code language: Python (python)

Output:

['It is secret!']
Code language: Python (python)

Use __dict__ to get class attributes

The above solution is great, but sometimes it comes shandy to have the attributes with their values. We can achieve that by calling __dict__ :

class Human(): age = 30 height = 180 eye_color ='blue' def __dir__(self): return ['It is secret!'] print(Human.__dict__)
Code language: Python (python)

Output:

{'__module__': '__main__', 'age': 30, 'height': 180, 'eye_color': 'blue', '__dir__': <function Human.__dir__ at 0x7ff07b41bdc0>, '__dict__': <attribute '__dict__' of 'Human' objects>, '__weakref__': <attribute '__weakref__' of 'Human' objects>, '__doc__': None}
Code language: Python (python)

The main advantage over __dict__ over the dir() function we saw before is that it is a dictionary; hence we can retrieve the key and/or values using standard dictionary functions.

Leave a Reply

Your email address will not be published. Required fields are marked *