How to use Python setattr()

The syntax of setattr() method is:

setattr(object, name, value)

In the following, we create a Person object with name "John" and then:
  • change the name to "Joy"
  • add age attribute




class Person():
    name = "John"
    
p = Person()
print(p.name) # print out "John"

setattr(p, "name", "Joy")
print(p.name) # print out "Joy"

setattr(p, "age", 29)
print(p.age) # print out 29



For getting an attribute of a object, then use getattr()

No comments:

Post a Comment