0
0
Pythonprogramming~5 mins

Modifying object state in Python

Choose your learning style9 modes available
Introduction

We change an object's state to update its information or behavior as the program runs.

When you want to update a person's age after their birthday.
When you need to change the speed of a car in a game.
When tracking the score in a quiz app and updating it after each question.
When toggling a light on or off in a smart home system.
Syntax
Python
object.attribute = new_value

# or using a method inside the class
def change_attribute(self, new_value):
    self.attribute = new_value

You can change an object's attribute directly or through a method.

Using methods to change state helps keep your code organized and safe.

Examples
Here, we directly change the age attribute of the Person object.
Python
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

p = Person('Anna', 30)
p.age = 31  # Directly changing the age
This example uses a method to safely update the person's age by adding 1.
Python
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def have_birthday(self):
        self.age += 1

p = Person('Anna', 30)
p.have_birthday()  # Using a method to update age
Sample Program

This program creates a Light object that starts off. The toggle method changes its state from off to on.

Python
class Light:
    def __init__(self):
        self.is_on = False
    
    def toggle(self):
        self.is_on = not self.is_on

light = Light()
print(f"Light is on? {light.is_on}")
light.toggle()
print(f"Light is on? {light.is_on}")
OutputSuccess
Important Notes

Changing object state means changing its attributes.

Use methods to control how the state changes for better code safety.

Summary

Objects have attributes that hold their state.

You can change state by assigning new values to attributes.

Methods help manage state changes cleanly and safely.