Get variable attribute python

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.

Get variable attribute python

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.

Get variable attribute python

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:

Human1 :  Mradula
0

 

Output:

Human1 :  Mradula
1

 

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: 

Human1 :  Mradula
2

 

Output:

Human1 :  Mradula
3

 

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

Human1 :  Mradula
4

 

Output:

Human1 :  Mradula
5

 

Note how each attribute is followed by its value.

b. Passing parameter to the vars() function

Human1 :  Mradula
6

 

Output:

Human1 :  Mradula
7

 

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:

Human1 :  Mradula
8

 

Output:

Human1 :  Mradula
9

 

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:

Get variable attribute python

Let's take an example for a 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__())
0

 

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

Output:

# 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__())
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.

How do you find the attribute of a variable in Python?

Python getattr() function is used to get the value of an object's attribute and if no attribute of that object is found, default value is returned. Basically, returning the default value is the main reason why you may need to use Python getattr() function.

How to get value by attribute name in Python?

Python getattr() The getattr() method returns the value of the named attribute of an object. If not found, it returns the default value provided to the function.

What does __ Getattribute __ do in Python?

__getattribute__ This method should return the (computed) attribute value or raise an AttributeError exception. In order to avoid infinite recursion in this method, its implementation should always call the base class method with the same name to access any attributes it needs, for example, object.

How do you access the attributes of an object in Python?

getattr() − A python method used to access the attribute of a class. hasattr() − A python method used to verify the presence of an attribute in a class. setattr() − A python method used to set an additional attribute in a class.