Introduction
We change an object's state to update its information or behavior as the program runs.
Jump into concepts and practice - no test required
We change an object's state to update its information or behavior as the program runs.
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.
age attribute of the Person object.class Person: def __init__(self, name, age): self.name = name self.age = age p = Person('Anna', 30) p.age = 31 # Directly changing the age
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
This program creates a Light object that starts off. The toggle method changes its state from off to on.
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}")
Changing object state means changing its attributes.
Use methods to control how the state changes for better code safety.
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.
color to 'blue'?class Box:
def __init__(self):
self.size = 5
def enlarge(self):
self.size += 3
b = Box()
b.enlarge()
print(b.size)class Car:
def __init__(self):
self.speed = 0
def accelerate(self):
speed += 10
c = Car()
c.accelerate()
print(c.speed)use() is called on an object. Which is the best way to modify the object state to do this?