Python built-in Method - setattr()
The setattr()
function is a built-in Python method that is used to set the value of an attribute on an object. The setattr()
function takes three arguments: the object whose attribute is to be set, the name of the attribute, and the value to be assigned to the attribute.
The syntax for the setattr()
function is as follows:
setattr(object, name, value)
object
: The object whose attribute is to be set.name
: The name of the attribute to be set.value
: The value to be assigned to the attribute.
Here are some examples of how the setattr()
function can be used:
>>> class MyClass: ... pass ... >>> obj = MyClass() >>> setattr(obj, "x", 42) >>> print(obj.x) 42
In this example, we define a simple class MyClass
. We then create an instance of the class obj
. We use the setattr()
function to set the value of the x
attribute on the obj
instance to 42. Finally, we print the value of the x
attribute on the obj
instance.
>>> class Person: ... def __init__(self, name): ... self.name = name ... >>> p = Person("Alice") >>> setattr(p, "age", 30) >>> print(p.age) 30
In this example, we define a class Person
with an __init__
method that takes a name
argument. We create an instance of the class p
with the name
attribute set to "Alice". We then use the setattr()
function to set the value of the age
attribute on the p
instance to 30. Finally, we print the value of the age
attribute on the p
instance.
The setattr()
function is a useful built-in method in Python that provides a convenient way to set the value of an attribute on an object at runtime. It can be particularly useful when working with dynamic data structures or when building complex object hierarchies.