Accessing Attributes of Class Objects

In this article, we will learn about classes, what the object of a class means, and how classes represent entities. We will also see attributes and accessing attributes of Class Objects using the python getattr() function and dot operator. So, Let’s start,

Classes

So, before understanding the getattr(), we need to understand classes and objects. First, let’s get a walkthrough of it.

As we all know, we use different parameters for the evaluation of real-world entities. For example, we use numbers to represent quantities. We use a group of characters to define identities, and more or less, everything can be characterized by the composition of these two. Similarly, in python, we have some objects used to represent entities. . We call them datatypes. Some of them are:

DatatypeDescription
IntegerUsed to represent integers.
FloatIt is used to represent decimals or floating-point numbers.
Complex NumberUsed to represent complex numbers.
StringIt is used to represent the collection of one or more characters.
ListThey are used in the collection of the same or different datatype edata types (mutable).
TupleThey are used in the collection of the same or different datatype elements (immutable).
SetThey are used in the collection of the same or different datatype elements without duplicacy.
BooleanUsed to represent True/False state.
DictionaryThey are used in the collection of data in key-pair format.

However, only using them for representation is not enough, just like in real life. So, there we make use of classes which are compositions of inbuilt datatypes or some other classes. To understand it better, let’s take an example of a car,

So, whenever we hear the word “car,” then we get an image of “Wheels,” “Engines,” “Seats,” e.t.c. Similarly, again for “Engines,” we have pistons, cylinders, combustion chambers e.t.c.
So, here we can say that to represent a car, we need some other entities, which may be atomic or composition of some other entities.

However, In programming, we can represent it using classes that may have atomic objects or derived objects. The syntax for defining a class is as follow:

class Car():
   int length,width,height   # atomic object
   Engine engine_object      # derived object 
   ...
   

Objects

Once we get a clear understanding of classes, let’s move to objects. To get a close view, we can say that defining class is like getting a design blueprint of the car, and initializing the car object in programming is like assembling the model of the vehicle.

The syntax for initializing the object is as follow:

car_object = Car()

Attributes of a Class

So, attributes are the values or function that is associated with any class or a datatype. In simple words, we can say that the properties defined in any class are called its attribute. For the above example, we can say that “length”, “width”, “height,” and “engine_object” are attributes of the car object as they are defining its property. However, getting access to them help us to do operations on the car object. So, We have several ways of doing that. We will look at each of them one by one.

Accessing Attributes of Class Objects using dot (“.”) operator

Let’s understand this using an example,

class PrintData:

    data = "Default data is accessed"

    def overwrite_data(self,data):
        self.data = data
        return self.data

obj = PrintData()   # Creating object for the class

accessed_data = obj.data    # Accessing data attribute of PrintData Class
print("Accessed Data: ",accessed_data)   

# Accessing print_data() method of PrintData Class
overwritten_data = obj.overwrite_data("Data Overwritten")
print("Data Overwritten: ",overwritten_data)

Output:
Accessed Data:  Default data is accessed
Data Overwritten:  Data Overwritten

Accessing Attributes of Class Objects using getattr() function

To access attributes using the getattr() function, we first need an object of the class. Once we create instantiate the class, we will use getattr() method. It has the following syntax:

Syntax:

getattr(<classObject>,<attribute_name>,<default[optional]>

The first argument of getattr() method is the object of the class, and the second argument is the name of the attribute we want to access. We can also pass a third argument which takes the default value which is returned when no attribute of the given name is found. However, it is optional to mention.

Let’s understand this with an example:

class PrintData:

    data = "Default data is accessed"

    def overwrite_data(self,data):
        self.data = data
        return self.data

obj = PrintData()   # Creating object for the class

# Accessing object using getattr() function
# class object passed as the first parameter, attribute name is the second parameter and 
# default is the third parameter which is optional.
accessed_data = getattr(obj,"data")
print("Accessed Data: ",accessed_data)   

# Accessing class method using getattr() function and passing parameters to the class method 
overwritten_data = getattr(obj,"overwrite_data")('Overwritten Data')
print("Data Overwritten: ",overwritten_data)

# For below call, object is obj 
# Attribute name is information which is available in PrintData class
# default value is "No information attribute is available"
information_data = getattr(obj,'information',"No information attribute is available")
print("Information data: ",information_data)

Output:

Accessed Data:  Default data is accessed
Data Overwritten:  Overwritten Data
Information data:  No information attribute is available

Accessing Attributes of Class Objects as Dictionary

We can also access attributes of class objects in the form of a dictionary. Here, Keys of the dictionary are names of the attributes, and values are values for the given attribute. Let’s understand this with an example:

Using __dict__

class PrintData:

    def __init__(self):
        self.data1 = "Data 1"
        self.data2 = "Data 2"

    def overwrite_data(self,data):
        self.data = data
        return self.data

obj = PrintData()

dict_ = obj.__dict__      # Returns object attribute in form of dictionary
print(dict_)                   # Printing dictionary
print(dict_['data1'])     # Accessing first element of dictionary
dict_['data1'] = 'Data 1 Overwritten'   # Overwriting first element of dictionary
print(dict_['data1'])

print(dict_['data2'])    # Accessing second element of dictionary

Output:

{'data1': 'Data 1', 'data2': 'Data 2'}
Data 1
Data 1 Overwritten
Data 2

Using Vars method

class PrintData:

    def __init__(self):
        self.data1 = "Data 1"
        self.data2 = "Data 2"

    def overwrite_data(self,data):
        self.data = data
        return self.data

obj = PrintData()
print(vars(obj))

Output

{'data1': 'Data 1', 'data2': 'Data 2'}

FAQs on Python getattr

Q1) How do I get all the attributes of an object in python?

We can get all the attributes of an object using several methods, using “__dict__“, “var“. They are stored in the form of dictionaries whose key is attribute name and value is the value of attributes. We can also access attributes using the attribute name in the “getattr()” method or using the dot” operator.

Q2) How to create a python dictionary from the objects field?

To create a python dictionary one can either use the “var” method or the “__dict__” property.

Conclusion

So, In this article, we learned about classes, objects, and different methods to access attributes for class objects.

To learn about accessing classes from different files: Click Here!

I hope this article has helped you. Keep Supporting. Thank You

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments