Introduction
In the previous lesson, you learned how to:
- Create methods inside a class
- Use
selfto access object data - Call methods on different objects
So far, our methods have only displayed information.
In this lesson, you’ll learn how methods can also change the data inside an object.
You will learn how to:
- Define multiple methods inside a class
- Use methods to update an object’s attributes
- Understand how an object’s state can change over time
What Is State?
The state of an object refers to the data it currently holds.
For example:
- A student’s name
- A student’s year group
- A student’s score
When a method changes one of these values, the state of the object changes.
Example: Updating an Object’s State
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
def add_points(self):
self.score += 10
student = Student('Alex', 50)
student.add_points()
print(student.score)
Here:
- The object starts with a score of 50
- The method
add_pointschanges the score - The object now stores a new value
Predict:
Look at the following code. What do you think will be printed?
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
def add_points(self):
self.score += 5
student = Student('Jamie', 40)
student.add_points()
student.add_points()
print(student.score)
Think about:
- How many times is the method called?
- Does the score reset or keep increasing?
Run:
Run the code below and check your prediction.
Investigate:
Now let’s investigate how multiple methods can affect the same object.
Try this:
- Add a new method called
remove_points - This method should subtract 5 from the score
- Call both methods in different orders
Use the editor below to experiment.
Think about:
- Does the order of method calls matter?
- Why does the object remember its updated score?
Modify:
The following program is meant to update the student’s score, but it contains an error.
Fix the code so the score changes correctly.
The problem
- The method does not update the object’s attribute
selfis missing when changing the score