Python is an object-oriented programming language which uses objects and classes. The fundamental idea behind OOPs is to bind the data and the functions that use it in such a way that no other portion of the code may access it. A class is basically a collection of objects and every object has some characteristics or attributes that are related to them. You must be aware of an object’s attributes in order to work effectively with it. In this tutorial, we will demonstrate how to print object attributes in Python in detail along with examples.
In this article, we will cover the following points:
- What is an object and attribute in terms of classes?
- Methods to access Object attributes in python
If you have a basic understanding of objects and attributes, then you can skip the first point.
If you want to learn more about Python Programming, Visit Python Programming Tutorials.
What is an object and Attribute in terms of Classes?
Object is an instance of class and attributes are simply the features or characteristics of an object. All objects (variable instances) of a class share these attributes. For instance, if an object is a human its attributes are complexion, height, gender, and many more.
Similarly, consider another example of fruits. Every fruit has some color and taste. Here, you can say that fruit is a class with two attributes color and taste. And mango, apple, banana, peach etc. are the objects of class fruit having these two attributes. In short, object act as variables that hold some data which can be a string or integer.
Now, lets understand how to construct and access objects and attributes. First of all, constuct a class WC_player_data with a __init__ built-in constructor. The class has two attributes: players_name and team. The _init_ method is a constructor for the class, which is called when a new instance of the class is created. It take the two attributes as a parameters and initializes them. The code below shows how you can create objects.
#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 the above example, p1, p2 and p3 are three objects of the class “WC_player_data”.
Methods to access Object Attributes
In the previous section, you have observed that we cannot access the attributes directly by printing the objects using print statement. So, the next question is how can we access these attributes and manipulate them. Here are some of the common methods to print the attributes of the object in Python.
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:
- Create an object that you want to print the attributes of.
- Call the
dir()method on the object, which will return a list of all its attributes and methods.
- Use a
forloop 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
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)
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.
--------------------------------------------------------------------------- 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.