Python Setattr() Method For Setting Attributes of An Object

Programming in Python involves working with multiple data structures at a time. According to the rule of thumb in python language, when functioning with a set of data which have a specific structure, you have to use the “class” function. Classes in Python have some predefined objects which are assigned some specific attributes, and those attributes hold some specific values. If we want to change those values and attributes, we use the “setattr()” function.

You can even use this function to change attributes of other objects like a list, dictionary, etc.

What Is setattr() Function?

In Python, you can use a constructor and an object function to assign values to a class variable. Besides, from that method, you can also use the “setattr()” function, which allows you to do the same.

How To Use This Function?

Python Setattr() Function

Python is an easy programming language, and so are its functions. Setattr requires three parameters:

  • Object: It is the specific variable whose value we want to change.
  • Name: A string storing the identification of the value we want to change.
  • Value: It is the actual value that we want to change.

Let’s understand more thoroughly with the help of an example:

Example 1

class Inventory: 
    name = "Servo Motor" # name is assigned as Servo Motor
    unit = 10 # value is set as 10
Motor = Inventory()
print(Motor.name)
print(Motor.unit)
setattr(Motor, 'unit', 15)
print(Motor.unit) 

Output:

Servo Motor
10
15

In this code, we changed the assigned value to the name by using the “setattr()” function. Moreover, we can change the name or the string holding that value, as shown in the example below.

Example 2

class Inventory: 
    name = "Servo Motor" # name is assigned as Servo Motor
    unit = 10 # value is set as 10
Motor = Inventory()
print(Motor.name)
print(Motor.unit)
setattr(Motor, 'name', "Stepper motor")
print(Motor.name) 

Output:

Servo motor
10
Stepper motor

We used “setattr()” to change the name of the object holding the value. As a result, the new name is assigned to that value.

Recommended Reading | [Solved] TypeError: β€˜str’ Object Does Not Support Item Assignment

How To Use setattr() with User Input?

Another way of using the “setattr()” function is to take user input to assign or change the attributes and values. To understand how to accomplish this task, let’s again take another example.

class Inventory:
    pass


Motor = Inventory()
name = input('Enter the attribute name:\n')
value = input('Enter the attribute value:\n')
setattr(Motor, 'Name', Value)
print(Motor.name)
print(Motor.value)

Output:

Enter the attribute name:
BLDC motor
Enter the attribute value:
25
BLDC motor
25

In this example, we declare a class with no attributes. Further, we take user input as attributes to the following user-given values and then use the “setattr()” function to assign those values.

Difference Between setattr() and assignment in Python

The main difference between the “setattr()” function and the assignment method is that you need to know the attribute of the object beforehand in the assignment, whereas, in the “setattr()” function, you don’t need to know the attribute beforehand you can directly assign the value.

Example 3

class Inventory: 
    name = "Battery" # name is assigned as Battery
    unit = 50 # value is set as 50
Electronics = Inventory()
Electronics.name = "Wires" 
Electronics.unit = 100 # In the above two lines we used assignment method
print(Electronics.name)
print(Electronics.unit)

Output:

Wires
100

In the example mentioned above, we can see how the assignment method is different from the method we discussed previously, and we already knew the attribute of the object.

Using python setattr() to Set an Attribute that Doesn’t Exist

We can use this function to set an attribute that doesn’t exist in our object because this function is dynamic in nature.

Example 4

class Inventory: 
    name = "Servo Motor" # name is assigned as Servo Motor
    unit = 10 # value is set as 10
Motor = Inventory()
print(Motor.name)
print(Motor.unit)
setattr(Motor, 'price' , 1500)# assigning an attribute that doesn't exist in class
print(Motor.price) 

Output:

Servo Motor
10
1500

From the given example, we can understand how you can set an attribute that doesn’t exist. If you want to know how to find if an object has any attributes, you can check this post.

python setattr() For Setting Private Variables

Private variables are values that can only be accessed under the private class or object. We can use “setattr()” function to set private attributes or variables. The method is shown below as an example.

Example 5

class Inventory:
    def _init_(self)
        self.__servo = 10
           
    def function(self)
        print(self.__servo)
        setattr(self, '__servo', 15)
        print(self.__servo)

if _name_ == "__main__"
    motor = Inventory()
    motor.function()

Output:

10
15

As seen in the example, you can use this function to assign or change an attribute but only inside that object or class. For a better understanding, you can refer to Python’s official documentation.

Error While Setting Attribute

When using “._setattr_”, if you try to override the function by only providing one parameter or providing surplus parameters, the code throws an error because “._setattr_” does not allow adding attributes to the object. It only allows adding attributes to subclasses, whereas “setattr()” even allows adding setting attributes to an object.

Going Recursive Using getattr()

If “setattr()” allows you to write any attribute, then “getattr()” allows you to read any attribute of the object. Its parameters are (object, name).

class Inventory(object):
    def __init__(self):
        self.servo = 10
        self.stepper = 20
           
    def _getattr_(self):
        x = int(getattr(self,'servo'))
        if (x < 20):
            y = int(getattr(self,'stepper'))
            print("Order value:" ,x+y)
                    
        
if __name__ == "__main__":
    order = Inventory()
    print(order._getattr_())

Output:

Order value: 30

From the code example, we can understand how we can use “getattr()” to read attributes and use it as a recursive function.

python setattr() Performance

Although this is a built-in function in Python, it has issues related to performance. It is relatively slower than other similar functions. On the other hand, it provides flexibility to users, which can be of great value when computing multiple data structures.

FAQs on Python Setattr

What is setattr() used for?

It is used for assigning or changing the attributes of any object.

What happens when no attribute is found in the setattr() function?

In this case, when no attribute is found, this function creates a new attribute and assigns the value to it.

Is setattr() static or dynamic in nature?

This function is dynamic in nature because it allows attributes to be defined after creating objects.

What is the use of the setattr() method in inheritance?

The use case of setattr() in inheritance is the same, i.e., to assign value to the attributes of an object.

Conclusion

There are many ways you can alter or assign attributes to an object, but when needed to be dynamically done, setattr() proves to be the best option. In this article, we have discussed various ways to use this function and how it is more advantageous in some use cases than other functions.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments