Python setattr() Built in Function

The setattr() function in Python sets the value of the specified attribute of the specified object. The syntax is:

setattr(object, name, value)

where object is any object that has attributes, name is a string that represents the name of an attribute and value is any value that can be assigned to an attribute.

Here are some examples of using setattr() with different objects:

# Create a class with two attributes
class Person:
    name = "John"
    age = 36


# Create an instance of Person
p = Person()

# Use setattr() to change the value of name
setattr(p, "name", "Jane")
print(p.name)
# Output: Jane

# Use setattr() to create a new attribute called country
setattr(p, "country", "Norway")
print(p.country)
# Output: Norway

# Use setattr() to assign None to an existing attribute
setattr(p, "age", None)
print(p.age)
# Output: None

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions