How to get all object attributes in Python
In this tutorial, we will see how to get all object attributes in Python.
Object Attributes in Python
Finding the attributes of an object returns a list of strings containing all of the object’s attributes.
One might even question what are object attributes?
Object attributes are the characteristics of an object. For instance, if an object is a car its attributes are color, price, speed, and many more.
However, in programming object attributes are also the same.
As there may be a lot of attributes for one object, to get the all attributes we use two approaches.
1) dir() function:
dir() function is an inbuilt function that will return a list of attributes and methods of any object.
Syntax :
print(dir(object_name))
2) vars() function:
vars() is an inbuilt function that will show all the attributes of a Python object. It takes one parameter, which is also optional. vars function takes an object as a parameter which can be an object, class having __dict__ attribute. If the object doesn’t match the attribute, a TypeError exception is raised.
vars function can be used when we require the attributes as well as the values.
Example:
def __init__(self, version, year): self.version = version self.year = year def usedpython(self, year): self.year += year p=Python(version=3, year=2018) print(vars(p))
We can see here that it returns a dictionary of the instance attributes of our object “p”
Output:
{'version': 3, 'year': 2018}
It works similarly to the __dict__ attribute, which returns a dictionary of all the instance attributes.
Explanation:
In this post, we learned how to print attributes of a python object with the help of two built-in functions which are dir() and vars().
Leave a Reply