The setattr() function is used to set 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 setattr() to Set an Attribute of an Object in Python
Below, a new car is created from the Car class defined earlier. It will have the default values of the car class:
blueToyota = Car()
The [setattr() function ](https://docs.python.org/3/library/functions.html#setattr) can be used to set the value of any attribute of the **Car** class:
setattr(blueToyota, 'colour', 'blue') setattr(blueToyota, 'make', 'Toyota')
Above, the value for the colour attribute for blueToyota is set to “blue”, correcting the default values to match the intended values for the new car.
You can also set attributes using dot syntax:
blueToyota.colour = blue
The changes can be confirmed using the getattr() function:
print(getattr(blueToyota, 'colour'))