What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

How to Print Object Attributes in Python? (with Code)

  • Oct 14, 2022
  • 8 Minutes Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Mradula Mittal
How to Print Object Attributes in Python? (with Code)

Python is an object-oriented programming language. In fact, everything in Python is an object (even a class)! Every object has some attributes associated with them. Now, to work well with any object you must know about its attributes.

Hence in this article, we'll discuss objects, attributes, and ways to print these objects' attributes in Python. So, let's get started.

What is an Object in Python?

An object is an instance of a class. It is often regarded as a real-world entity. An object may constitute properties, data (or), and a few methods to operate on that data. It is needed to instantiate a class. Each object has a unique identity.

For instance, consider the human race as a class. So each human will have a name, age, weight, height, and many other properties. Each person can be uniquely identified as an object, (including me, you, your friend, or any other human you know!)

Let's take an example of how to declare an object in Python:

# defining class human
class human:
    def __init__(self, name, age):
        self.name = name
        self.age = age


# creating an instance of class human
human1 = human("Mradula", 20)
human2 = human("Jennifer", 24)

# accessing object
print("Human1 : ", human1.name)

 

Note that the name and age variables are attributes of the objects of class 'human'.

Output:

Human1 :  Mradula

 

The above example displays how an object is created (for a user-defined class) and accessed in Python. We have also declared attributes of the object (here, human1 & human2) and accessed them.

declare object attributes

Now, we should take a better look at the attributes of an object.

What is an Attribute in Python?

An attribute can be defined as a property of a class or an object. These are data members inside a class (or object) that represents their features. These attributes can be properties (state or value) defining an object or any method acting upon that object.

For instance, let's take our previous example: class human. The name and age variables declared in the class human are actually 'attributes' of 'human'. Along with them, actions (functions) like running, sleeping, reading, walking, and swimming are also attributes of 'human'. 

You might get confused between an attribute and an object. The difference between an object and an attribute is that An object is a real-world entity while an attribute is a characteristic of that object.

person and object

These attributes are generally defined within a class and shared among all the instances (objects) of that class. An object can be accessed using these attributes.

Attributes are also classified into two types:

  1. Class Attributes
  2. Instance (object) Attributes

An Instance attribute is a data member of an object. It is associated with the properties of an object. So, every instance of that class will have the same instance attributes. (It is the purpose of a class, after all!). Their scope of access also lies within the object creation.

For instance, refer to the variables 'name' and 'age' of class 'human'. These are instance variables, allocated to every object separately.

Class Attributes is a data member of the whole class. These attributes share the same memory space and are accessed by all the objects in common.

To learn more about attributes, check our article on static variables in python.

Now that we have learned about objects and attributes, we're all set to learn how to print all attributes of an object in Python.

4 Ways to Print all Attributes of an Object in Python

In order to code efficiently and access an object to obtain its full functionality, one must be aware of all the attributes of the object. Thus, given below are different ways to print all attributes of an object in Python.

01) Using __dir__() method

Python offers an in-built method to print out all attributes of an object (Now, this object may be anything in Python). This method is also known as a magic method or a dunder method in Python.

Syntax:

print(objectName.__dir__())

Let's jump on to an example for better understanding:

# listing out all attributes of an object in Python
# create a class
class Student:
    def __init__(self, name, id, age):
        self.name = name
        self.id = id
        self.age = age

    def info(self):
        return f"Student name: {self.name} and id: {self.id} "

    # class variable
    var = 1


# creating object
s1 = Student("Mradula", 1, 20)
s2 = Student("Joel", 2, 15)
print(s1.info())
print(s1.__dir__())

 

Output:

Student name: Mradula and id: 1
['name', 'id', 'age', '__module__', '__init__', 'info', 'var', '__dict__', '__weakref__', '__doc__', '__repr__', '__hash__', '__str__', '__getattribute__', '__setattr__', '__delattr__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__new__', '__reduce_ex__', '__reduce__', '__subclasshook__', '__init_subclass__', '__format__', '__sizeof__', '__dir__', '__class__']

 

Note that the method returns a list with the user-defined attributes given priority.

You'll be surprised to know that, the __dir__() method can also be modified. You can define the __dir__() method in a class to override the default __dir__() method. Let's modify the __dir__() method for the above example:

# listing out all attributes of an object in Python
# create a class
class Student:
    # defining the __dir__() method
    def __dir__(self):
        return [1, 2, 10, 5, 9]

    # class variable
    var = 1

# creating object
s = Student()
# calling the __dir__() method
print(s.__dir__())

 

Output:

[1, 2, 10, 5, 9]

 

The s.__dir__() statement calls for the user-defined method which overrides the default dunder method. Notice how different the outputs of the default __dir__() method and the user-defined __dir__() method are.

02) Using dir()

Python offers an in-built function to list out all the attributes of an object. This function returns all attributes (variables, methods, or objects) associated with the passed parameter, in a given scope.

Syntax:

print(dir(parameter))

Passing the parameter is optional. If you don't pass a parameter, the dir() function will return all the attributes in the local scope.

Let's take an example:

# listing out all attributes of an object in Python
name = "FavTutor"
article = "Printing Object's attributes"

# calling dir() function with no argument
print(dir())

 

Output:

['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'article', 'name']

 

See! The dir() function returned all the in-built and user-defined attributes in the local scope.

Although the above example had a small list, sometimes the output is long enough to have low readability. To deal with this, Python offers a pprint module.

The "pprint module" is used to print the list in a well-formatted way. Take a look at the example below.

Example: To print the attributes of objects in Python by using the dir() function with an object as an argument.

# listing out all attributes of an object in Python
# importing pprint module
from pprint import pprint

# create a class
class Student:
    def __init__(self, name, id) -> None:
        self.name = name
        self.id = id

    def info(self):
        return f"Student name: {self.name} and id: {self.id} "

    # class variable
    var = 1


# creating object
s1 = Student("Mradula", 1)
print(s1.info())

# List out all attributes of the object using pprint()
pprint(dir(s1))

 

Output:

Student name: Mradula and id: 1
['__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__',
 'id',
 'info',
 'name',
 'var']

 

The pprint() method relates directly to "pretty print"! Take note of how each feature is printed on a separate line. This improves the output's readability.
Now that we've seen some dir() examples, let's go over some key points about the dir() function:

  1. It returns a list of all the characteristics of an object in the local scope.
  2. It internally invokes the __dir__() function. Internally, the dir() function implements its functionality via the __dir__() method.
  3. The dir() function provides an alphabetically sorted output.

Before moving to the next method, let's compare the dir() and __dir__() methods.

Working with dir() function and __dir__() method

a. You already know that the dir() function internally calls for __dir__() method for implementation. Hence, defining the __dir__() method will also change the functionality (and hence output) of the dir() function. Let's take the above example and call the dir() method:

# listing out all attributes of an object in Python
# create a class
class Student:
    # defining the __dir__() method
    def __dir__(self):
        return [1, 2, 10, 5, 9]

    # class variable
    var = 1

# creating object
s = Student()

# calling the __dir__() method
print("The __dir__() method returns: ", s.__dir__())
# calling the dir() method
print("The dir() method returns: ", dir(s))

 

Output:

The __dir__() method returns:  [1, 2, 10, 5, 9]
The dir() method returns:  [1, 2, 5, 9, 10]

 

Notice the difference between the outputs returned by dir() function and the __dir__() method. While the __dir__() method provides the defined list as-it-is, the dir() function produces a sorted list of attributes.

b. Now let's take another example of modifying the __dir__() method. You'll be surprised by the output: 

# listing out all attributes of an object in Python
# create a class
class Student:
    # defining the __dir__() method
    def __dir__(self):
        return [1, 2, 10, 5, 9, "alice"]

    # class variable
    var = 1


# creating object
s = Student()

# calling the __dir__() method
print("The __dir__() method returns: ", s.__dir__())
# calling the dir() method
print("The dir() method returns: ", dir(s))

 

Output:

The __dir__() method returns:  [1, 2, 10, 5, 9, 'alice']
Traceback (most recent call last):
  File ".\temp.py", line 18, in <module>
    print("The dir() method returns: ", dir(s))
TypeError: '<' not supported between instances of 'str' and 'int'

 

The __dir__() method works fine but the dir() function produces a TypeError. You must be wondering WHY!

The code did work for the previous example, didn't it? So why the error? Because the dir() method compares the attributes to produce a sorted list as output. Hence, since the types, string ("alice") and integer (1,2 and rest), cannot be compared with each other, therefore calling dir() method on this produces an error.

Note: The dir() function, in absence of the __dir__() method, calls for the __dict__ attribute to return a list of all the attributes of an object in Python.

 03) Using vars() function

Python offers the vars() function which returns a 'dictionary' of all the instance attributes along with their values. It is similar to the above methods, the only difference being, vars() focuses only on instance attributes and also returns their values along with them.

Syntax:

print(vars(objectName))

Passing any parameter to the vars() function is optional. It can also be called without passing any parameter to it.

Let's take a few examples to understand the different cases:

a. Without passing any parameter

# listing out all attributes of an object in Python

# import pprint module
from pprint import pprint

# create a class
class Student:
    # class variable
    var = 1

    def __init__(self, name, age, id):
        self.name = name
        self.age = age
        self.id = id


# creating object
s = Student("Alice", 14, 23)

# calling the vars() function
pprint(vars())

 

Output:

{'Student': <class '__main__.Student'>,
 '__annotations__': {},
 '__builtins__': <module 'builtins' (built-in)>,
 '__cached__': None,
 '__doc__': None,
 '__file__': '.\\temp.py',
 '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x000002201CCBEB08>,
 '__name__': '__main__',
 '__package__': None,
 '__spec__': None,
 'pprint': <function pprint at 0x000002201CD04828>,
 's': <__main__.Student object at 0x000002201CD0EAC8>}

 

Note how each attribute is followed by its value.

b. Passing parameter to the vars() function

# listing out all attributes of an object in Python

# import pprint module
from pprint import pprint

# create a class
class Student:
    # class variable
    var = 1

    def __init__(self, name, age, id):
        self.name = name
        self.age = age
        self.id = id


# creating object
s = Student("Alice", 14, 23)

# calling the vars() function
pprint(vars(s))

 

Output:

{'age': 14, 'id': 23, 'name': 'Alice'}

 

When the object (here s) is passed as an argument to the vars() method, it produces a dictionary of only the attributes associated with the instance, leaving out the rest of the attributes (as obtained in the above example).

Also, note that the vars() function internally calls for the __dict__ attribute for implementation. The __dict__ attribute is simply a dictionary containing all attributes of that object.

Let's look at the output when we use the __dict__ attribute in the above example:

# listing out all attributes of an object in Python
# create a class
class Student:
    # class variable
    var = 1

    def __init__(self, name, age, id):
        self.name = name
        self.age = age
        self.id = id


# creating object
s = Student("Alice", 14, 23)

# calling the __dict__ attribute
print(s.__dict__)

 

Output:

{'name': 'Alice', 'age': 14, 'id': 23}

 

The output is same! (Hence, remember that the vars() function will produce an error when passed over an object which does not have the __dir__ attribute.)

04) Using inspect module

The inspect module in Python helps in inspecting certain modules or objects that are included in the code. It includes several useful functions that provide information about live objects (like class, function, object, and methods). It can be used to obtain an analysis of objects, for example, to examine a class's content or to display information about an object.

To print all the attributes of an object in Python, you can use the 'getmembers()' function of the inspect module. This function returns the list of tuples containing the attributes along with their values.

Refer to the below image for better readability of the output:

attribute value

Let's take an example for a better understanding:

# listing out all attributes of an object in Python

# let's use the pprint module for readability
from pprint import pprint

# import inspect module
import inspect

# create a class
class Student:
    # class variable
    var = 1

    def __init__(self, name, age, id):
        self.name = name
        self.age = age
        self.id = id


# creating object
s = Student("Alice", 14, 23)

# calling getmembers() function of the inspect module
# passing object s as parameter
pprint(inspect.getmembers(s))

 

I've used pprint module to increase the readability of the output.

Output:

[('__class__', <class '__main__.Student'>),
 ('__delattr__',
  <method-wrapper '__delattr__' of Student object at 0x0000020FA28EEB48>),
 ('__dict__', {'age': 14, 'id': 23, 'name': 'Alice'}),
 ('__dir__', <built-in method __dir__ of Student object at 0x0000020FA28EEB48>),
 ('__doc__', None),
 ('__eq__', <method-wrapper '__eq__' of Student object at 0x0000020FA28EEB48>),
 ('__format__',
  <built-in method __format__ of Student object at 0x0000020FA28EEB48>),
 ('__ge__', <method-wrapper '__ge__' of Student object at 0x0000020FA28EEB48>),
 ('__getattribute__',
  <method-wrapper '__getattribute__' of Student object at 0x0000020FA28EEB48>),
 ('__gt__', <method-wrapper '__gt__' of Student object at 0x0000020FA28EEB48>),
 ('__hash__',
  <method-wrapper '__hash__' of Student object at 0x0000020FA28EEB48>),
 ('__init__',
  <bound method Student.__init__ of <__main__.Student object at 0x0000020FA28EEB48>>),
 ('__init_subclass__',
  <built-in method __init_subclass__ of type object at 0x0000020FA2A5A5E8>),
 ('__le__', <method-wrapper '__le__' of Student object at 0x0000020FA28EEB48>),
 ('__lt__', <method-wrapper '__lt__' of Student object at 0x0000020FA28EEB48>),
 ('__module__', '__main__'),
 ('__ne__', <method-wrapper '__ne__' of Student object at 0x0000020FA28EEB48>),
 ('__new__', <built-in method __new__ of type object at 0x00007FFA0CFEA820>),
 ('__reduce__',
  <built-in method __reduce__ of Student object at 0x0000020FA28EEB48>),
 ('__reduce_ex__',
  <built-in method __reduce_ex__ of Student object at 0x0000020FA28EEB48>),
 ('__repr__',
  <method-wrapper '__repr__' of Student object at 0x0000020FA28EEB48>),
 ('__setattr__',
  <method-wrapper '__setattr__' of Student object at 0x0000020FA28EEB48>),
 ('__sizeof__',
  <built-in method __sizeof__ of Student object at 0x0000020FA28EEB48>),
 ('__str__',
  <method-wrapper '__str__' of Student object at 0x0000020FA28EEB48>),
 ('__subclasshook__',
  <built-in method __subclasshook__ of type object at 0x0000020FA2A5A5E8>),
 ('__weakref__', None),
 ('age', 14),
 ('id', 23),
 ('name', 'Alice'),
 ('var', 1)]

 

Note that this list contains tuples in sorted order. So, the getmembers() function returns a sorted list of all the attributes of an object in Python, along with their respective values.

Conclusion

So far we've discussed different ways to print all attributes of an object in Python. But before moving on to list out all the attributes, you must be able to differentiate between instance attributes and class attributes. So, try and test out these methods along with their variations to understand them better.

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Mradula Mittal
I'm Mradula Mittal, a tech community enthusiast with a knack for content writing. Always eager to learn more about Python and Machine Learning. Having an analytical brain, I'm particular about my research and writing. I live by the motto "the more you share, the more you learn" and being a techie, it's fun to learn, create and share.