The getattr() function is used to get the value of an attribute of an object. Here is how it is used, with examples.
Python Objects and Classes
Python is an object oriented programming language. Object oriented means that rather than code being written as a list of instructions, accumulating data and passing the results to the following lines of code (known as procedural programming), data and functionality is contained within the objects it describes. Each object is a self-contained representation of something, that can be modified, and passed between functions in a non-procedural/non-linear manner.
A class is a consistent kind of object, which defines the fixed attributes and methods used to interact with it. This is useful as if we know that all objects of a certain class contain the same data and behave the same way, we know what we can and can’t do with them elsewhere in the code.
So, for example, you might have a Car class, which has the attributes of make, year, and colour. In Python, classes are defined like this:
class Car: make = "Ford" year = 2000 colour = "red" def repaint(self): self.colour = "yellow"
Now, whenever we encounter an object of the class Car, we know exactly what the data inside will look like, regardless of the actual contents. We know that we can access a colour attribute and that that information will be present.
Object Attributes and Methods
Above, a Car class is defined, with some attributes (also known as properties) – the variables stored within it which are used to describe it (make, year, colour), and a method, a function contained within the class that can be used to interact with it – in this case the repaint() method changes the colour of the car.
The attributes shown above are the default values for the class. Once the class has been defined, objects can be instantiated (created) from that class. They will all share the same attributes and methods, and so can be treated in the same way, no matter where they appear in your code, or the differences of the values within the objects.
Using getattr() to Get an Attribute of an Object in Python
Below, a new car is created from the Car class defined earlier:
blueToyota = Car()
The getattr() function can be used to get the value of any attribute of the Car class:
…and printed using the print() function:
You can also access attributes using dot syntax:
But – we want to describe a blue Toyota, not the default red Ford. Attributes can be updated using dot notation also:
blueToyota.colour = "blue" blueToyota.make = "Toyota"
The change can be confirmed using the getattr() function: