Python setattr()
Python setattr() builtin function is used to set an attribute with a value for given object. If the attribute already exists, then the value is updated with the new value. If the attribute is not present, new attribute for the object is created, if the object allows.
In this tutorial, we will learn about the syntax of Python setattr() function, and learn how to use this function with the help of examples.
Syntax
The syntax of setattr() function is
setattr(object, name, value)
where
Parameter | Required/ Optional | Description |
---|---|---|
object | Required | A Python object. |
name | Required | A string. Name of the attribute. |
value | Required | The value that is to be assigned to the attribute of object. |
Returns
The function returns None.
Examples
1. Set New Attribute
In this example, we define a class A
with two attributes: name
and count
. Then we shall set an attribute available
with True
. To verify if the variable is set, we print the attribute to console.
Python Program
class A:
name = 'Apple'
count = 25
setattr(A, 'available', True)
print(A.available)
Output
True
2. Set Existing Attribute with New Value
In this example, we define a class A
with two attributes: name
and count
. Then we shall set the attribute name
with Banana
.
Python Program
class A:
name = 'Apple'
count = 25
setattr(A, 'name', 'Banana')
print(A.name)
Output
Banana
Conclusion
In this Python Tutorial, we have learnt the syntax of Python setattr() builtin function, and also learned how to use this function, with the help of Python example programs.