Concept Flow - Modifying object state
Create object
Access object attribute
Modify attribute value
Use updated object state
End
This flow shows how an object is created, its attribute accessed and modified, then used with the updated state.
Jump into concepts and practice - no test required
class Car: def __init__(self, color): self.color = color my_car = Car('red') my_car.color = 'blue' print(my_car.color)
| Step | Action | Object State (color) | Output |
|---|---|---|---|
| 1 | Create Car object with color 'red' | color='red' | |
| 2 | Modify my_car.color to 'blue' | color='blue' | |
| 3 | Print my_car.color | color='blue' | blue |
| 4 | End of program | color='blue' |
| Variable | Start | After Step 1 | After Step 2 | Final |
|---|---|---|---|---|
| my_car.color | undefined | red | blue | blue |
Modifying object state: - Create object with attributes - Access attribute via object.attribute - Assign new value to attribute to update state - Updated attribute reflects in later use - Changes affect only that object instance
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?