Python setattr
- User
Python setattr
- Assistant
The
setattr()function in Python is used to set the value of a named attribute of an object. The syntax forsetattr()is as follows:setattr(object, name, value)Here,
object: The object whose attribute value needs to be setname: The attribute name that needs to be setvalue: The value to be assigned to the attribute
For example, consider the following code snippet:
class Car: def __init__(self, make, model): self.make = make self.model = model my_car = Car('Ford', 'Mustang') setattr(my_car, 'make', 'Chevrolet') print(my_car.make)Output:
ChevroletIn this example, we created a
Carclass with two attributes:makeandmodel. Then, we instantiated aCarobjectmy_carwithmakeas'Ford'andmodelas'Mustang'.We then used
setattr()function to setmy_car'smakeattribute to'Chevrolet'. Finally, we printed the value ofmy_car'smakeattribute, which is'Chevrolet'.Note that you can also use the dot notation to set an object's attribute in Python. For example,
my_car.make = 'Chevrolet'would achieve the same result assetattr(my_car, 'make', 'Chevrolet'). However, usingsetattr()is useful in situations where the attribute name is determined at runtime and needs to be passed as a string argument.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.