How to Print Object’s Attributes in Python

Python is an object-oriented programming language that revolves around the concept of objects and classes. The fundamental idea behind object-oriented programming is to encapsulate data and the functions that operate on it, ensuring no other portion of the code may access it. A class is a blueprint for creating objects, and each object possesses its own set of attributes or characteristics. Understanding an object’s attributes is crucial for efficient programming. In this tutorial, we will explore how to print object attributes in Python, providing detailed explanations and examples.

When working with objects in Python, it’s often useful to examine their attributes to understand their structure and available data. To print all the attributes of an object in Python, you can use the built-in dir() function, vars() functions or inspect module. By using these techniques, you can easily print and explore the attributes of an object, gaining valuable insights into its properties and behavior.

In this article, we will explore the concept of objects and attributes in Python classes. We will discuss what an object is and how attributes are associated with it. Additionally, we will delve into various methods for accessing object attributes in Python. By the end of this article, you will have a clear understanding of object-oriented programming principles and be equipped with techniques to effectively access and work with object attributes in your Python programs.

If you want to learn more about Python Programming, Visit Python Programming Tutorials.

WHAT iS AN OBJECT AND ATTRIBUTE ?

Object is an instance of class and attributes are simply the features or characteristics associated with that object. For example, in the context of humans, attributes can include complexion, height, gender, and many more.

Similarly, consider another example of fruits. Every fruit has its own color and taste. We can think of “fruit” as a class with two attributes: color and taste. Mango, apple, banana, peach, etc. can be seen as objects of the “fruit” class, each having its own specific values for color and taste. In short, object act as variables that store data which can be in the form of strings, integers, or other types. 

Now, let’s understand how to create and access objects and their attributes. We will start by constructing a class called “WC_player_data” with a built-in constructor method called “init“. This constructor method takes two attributes, “players_name” and “team”, and initializes them when a new instance of the class is created. To create objects of the `WC_player_data` class, we use the class name followed by parentheses, passing the appropriate values for the constructor parameters.

The following code demonstrates the creation of objects using this class:

#create a class
class WC_player_data:
   def __init__(self, players_name, team):
       self.players_name = players_name
       self.team = team
       
# creating an object of class 
p1 = WC_player_data('Fakhar Zaman','Pakistan')
p2 = WC_player_data('JN Malan','South Africa')
p3 = WC_player_data('JC Buttler','England')

print(p1)
<__main__.WC_player_data object at 0x7fa698cba8b0>

In this case, three objects `p1`, `p2`, and `p3` are created with different player names and teams. Finally, we print `p1`, which will display the memory address of the object.

METHODS TO PRINT aLL ATTRIBUTES oF aN OBJECT iN PYTHON

In the previous section, we observed that we cannot directly access the attributes by printing the objects using the print statement. So, the next question is how we can access and manipulate these attributes. There are several methods available to print the attributes of an object in Python. Some common methods include using the built-in dir() function, the vars() function, and the getattr() function. These methods allow us to retrieve and display the attributes of an object. Lets discuss them in detail.

Printing Object’s Attributes in Python using the dir() method

Python provides an inbuilt function dir() that lists all the attributes and methods of an object. To print the object’s attributes, you can use the following steps:

  1. Create an object that you want to print the attributes of.
  2. Call the dir() method on the object, which will return a list of all its attributes and methods.
  3. Use a for loop to iterate over the list of attributes and print each one.
class Rectangle:
    def __init__(self, x, y):
        self.height = x
        self.width = y

# Step 1: Create an object
my_object = Rectangle(10, 20)

# Step 2: Call the dir() method
attributes = dir(my_object)

# Step 3: Print the attributes
for attribute in attributes:
    print(attribute)

In the above example, my_object is an instance of a “Rectangle” class. Running the above code will print all the attributes and methods associated with this object. Another method is to use _dir_() method. Both methods return a list of the object’s attributes, but _dir_() is a special method that can be defined in an object to customize the behavior of the dir() function. We define the special _dir_() method in the Rectangle class to customize the list of attributes returned by the dir() function.

class Rectangle:
    def __init__(self, x, y):
        self.height = x
        self.width = y

    def __dir__(self):
        return ['height', 'width']

# Step 1: Create an object
my_object = Rectangle(10, 20)

# Step 2: Call the dir() method
attributes = dir(my_object)

# Step 3: Print the attributes
for attribute in attributes:
    print(attribute)
height
width

In this case, when we call the dir() function on my_object, we only return the attributes ‘height’ and 'width‘. On the other hand, dir() method prints all the attributes including builtin attributes of the class and methods of a class.

PRINT OBJECT’S ATTRIBUTES IN PYTHON USING VARS()

Another method is to use var() method to access the object attributes in Python. Pass the object as a parameter to the vars() function. It returns the object attributes in the dictionary format i.e., key-value pair.

def printAttributes(my_object):
  # Using vars() function
  attributes = vars(my_object)
  for attribute, value in attributes.items():
    print(attribute, "=", value)

class Employee:
    def __init__(self, name, ID, department):
        self.name = name
        self.ID = ID
        self.department = department

e1 = Employee('David John', 234, 'Finance')
e2 = Employee('Madrid Lucas', 321, 'Information Technology')

#print object e1 attributes
print("Attributes of Employee 1: ")
printAttributes(e1)

#print object e1 attributes
print("Attributes of Employee 2: ")
printAttributes(e2)
Attributes of Employee 1: 
name = David John
ID = 234
department = Finance
Attributes of Employee 2: 
name = Madrid Lucas
ID = 321
department = Information Technology

GETATTR() METHOD TO PRINT AN OBJECT’S ATTRIBUTES IN PYTHON

The attributes of an object can also be accessed and printed using Python’s getattr() function. The getattr() function takes two arguments: the object to retrieve the attribute from, and the name of the attribute to retrieve.

Here is the step-by-step demonstration about how the getattr() method works.

  • Define a class having the name ‘Car’. 
  • Define a class constructor __init__ () and pass an instance for the object as a parameter to it. 
  •  Now create an object “my_car”. 
  • Invoke a getattr() and pass the name of the object as a first argument and the attribute you want to access as the second argument.
  • Using the print function, you can print the value of that attribute.
class Car:
    def __init__(self, x, y, z):
        self.brand = x
        self.model = y
        self.year =  z
        
my_car = Car('BMW', 'X5', 1999)

# Using getattr() to print object attributes
print(getattr(my_car, 'brand'))
print(getattr(my_car, 'model'))
print(getattr(my_car, 'year'))
BMW
X5
1999

It returns the default value if no attribute for the object is found. For example If you will pass the color as a second argument to the getattr() function, the program will raise an attribute error.

print(getattr(my_car, 'color'))
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-10-6f114a920f87> in <module>
----> 1 print(getattr(my_car, 'color'))

AttributeError: 'Car' object has no attribute 'color'

Printing object attributes is necessary to perform computations on them. However, using dir(), __dir()__, vars() and getattr() methods, you can easily access all the attributes of an object and analyze them. If you have any queries regarding this topic, contact us.

Leave a Comment

Your email address will not be published. Required fields are marked *