When we use the object oriented concepts of python enough programming, we need to create objects and access their attributes. The objects are usually created from a class and the getattr function helps us in accessing the attributes of the object.
In the below example we create a object from a class call Best Buy and we assign values to the attributes of that object. Then we access those tributes in the print statements shown below.
import time # declare class class bestpy: name = "pyexperts" course = "python" # initialize object n = bestpy() # use of getattr to print name getattr_bestpy = time.time() print("The Company name is :" + getattr(n,'name')) print("getattr_bestpy time execution is : " + str(time.time() - getattr_bestpy),"\n") # use of conventional method to print course conventional_bestpy = time.time() print("It provides work on " + n.course) print("conventional_bestpt time execution is:" + str(time.time() - conventional_bestpy))
Running the above code gives us the following result −
The Company name is :pyexperts getattr_bestpy time execution is : 0.0011477470397949219 It provides work on python conventional_bestpt time execution is: 0.0002818107604980469