The exciting object-oriented programming world may appear to be overwhelming, especially when you have just started your Python journey. However, if you know to start small and work up slowly, you will realize that it is not that challenging.
A good way to build a basic understanding like this is to learn to print object attributes in Python first. That is why we prepared this article for you.
To Print Object Attributes In Python
Here is the sample code to print object attributes in Python:
#Defining a class and declaring its attributes
class Person:
def __init__(obj, fullname, yearofBirth, nationality):
obj.fullname = fullname
obj.yearofBirth = yearofBirth
obj.nationality = nationality
#Declare an Person object
wrkarma = Person(fullname='Karma', yearofBirth = 2000, nationality = 'US')
#Solution1: Using dir() to print object attributes in python
print('Results when using dir():', dir(wrkarma))
#Solution2: Using var() to print object attributes in python
print('Results when using var():', vars(wrkarma))
Output
Results when using dir(): ['__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__', 'fullname', 'nationality', 'yearofBirth']
Results when using var(): {'fullname': 'Karma', 'yearofBirth': 2000, 'nationality': 'US'}
Using dir()
There is no denying that the easiest method to access any object attribute in Python is through the dir()
function. After all, it is directly integrated into the base Python model, so the need to import additional libraries is non-existent.
Its syntax is very simple:
dir(object)
As you can see, it only has one input variable, object. This input can be any user-defined object or set, list, dictionary, tuple, etc. The returned value of dir() is a list of attributes available in the object.
Using vars()
Some of you may have quickly realized a big problem inherent to the dir() function. It will print all of an object’s attributes with no option to customize. That is not the case if you utilize the vars() function.
vars() differ from dir() in that it only prints out the instance attributes and their values. The reason lies in the way this function operates. vars() access an attribute called __dict__, which provides all the instance attributes in a dictionary.
To be more specific, __dict__ refers to a mapping object’s dictionary, storing all of that object’s writable attributes.
As you can guess, due to this uniqueness, vars() can’t work if the object passed into it doesn’t have the __dict__ attribute. That is why it will only raise an exception and flag TypeError. This is among the most seen issues of Python coding, alongside the Keras AttributeError.
Another special thing about this function is the fact that it can also act like local(). All you need to do is not pass any argument into vars().
Conclusion
This article has shown you all there is to know about how to print object attributes in Python. If you can grasp both approaches that we have provided, you will find that it is much easier to manipulate classes and objects. This ability is especially vital if you want to advance more in the world of object-oriented programming.