Python program to Get all object attributes

In this post, I’ll explain to you how you can get all object attributes in Python.

Object Attributes in Python

Object or instance attributes are the variables that can belong to only one object. Using these object attributes we can access class attributes. Every class instance points to its own attribute variable.

Like I have shown below:-

# declare a class in python and it's attributes
class Student:
    name = 'Mohit'
    rollNo = 45
    marks = 87
# s1 is an object attribute or an object of cladd Student
s1 = Student()
# we have access the name attribute of Student class using object attribute
print(s1.name)

Output:-

Mohit

Accessing all object attributes in Python

Now in order to access all object attributes, we have various methods like we can use in-built function dir()  or __dict__ a dictionary object to store object attributes or we can also use getattr() function to do it.

Here I’ll explain to you two methods using the dir() method.

For 

Using dir():-

dir() is a Python in-built function using which we can access the list of attributes for the object. It’ll return a list of all attributes in string.

Also read:

We’ll use dir() function to get all attributes of the object as below:-

#Python program to get all object attributes
#  declare a class in python and it's attributes
class Student:
    # class attributes
    name = 'Mohit'
    rollNo = 45
    marks = 87
    #method
    def __init__(self):
        print('Hello Wolrd')


# s1 is an object attribute or an object of cladd Student
s1 = Student()
attributes_of_s1=dir(s1)
#using dir() we have access all the object attributes
#it'll print all object attributes
print(attributes_of_s1)

Output:-

Hello World
['__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__', 'marks', 'name', 'rollNo']

Also read: Internal Python Object Serialization using marshal

Leave a Reply

Your email address will not be published.