Update Properties of Class Objects in Python
Update Properties of Class Objects
We can update properties of a class object using dot operator. Get the reference to the property of class object using dot operator .
and assign a new value to this property using Assignment Operator =
.
For example, if object1
is a class object in Python, then to update its property property1
, with value value1
, use the following syntax.
object1.property1 = value1
Example
Let us take an example scenario where we have a class named Person
with two properties: name
, age
.
We create an object person1
of type Person
, with some initial values for its properties: Person('Mike', 22)
.
Then, we shall update the property age
using the above specified syntax.
Python Program
class Person:
def __init__(self, name="NA", age="0"):
self.name = name
self.age = age
def printDetails(self):
print("Person Details")
print("Name :", self.name)
print("Age :", self.age)
person1 = Person("Mike", 22)
#for some reason we need to update age
person1.age = 35
person1.printDetails()
Output
Person Details
Name : Mike
Age : 35
Summary
In this Python Classes and Objects tutorial, we learned how to update properties of a class object.