Classes and objects
Instance methods and state
Place behavior next to the data it uses.
Lesson 50 of 63
Reading: about 1 min
Lesson + practice: about 15 min
Difficulty: Intermediate
On this page5 sections
An instance method receives self so it can read or update that particular object. A method should maintain a clear rule for the object’s state.
Worked example
class StudyPlan:
def __init__(self):
self.minutes = 0
def add(self, value):
if type(value) is not int or value <= 0:
raise ValueError("positive integer required")
self.minutes += value
plan = StudyPlan()
plan.add(20)
plan.add(25)
print(plan.minutes)45
Why this works
plan.add(20) passes plan as self. Validation happens before mutation, so invalid input leaves the total unchanged.
Another case
class Counter:
def __init__(self):
self.value = 0
def increment(self):
self.value += 1
c = Counter()
c.increment()
print(c.value)1
Practice
Call plan.add(0) inside try/except, then inspect plan.minutes.
Check the practice result
Reveal answer
It raises ValueError and the total remains 45.
Try another case
What does plan.add("10") do?
Check your answer
Reveal answer
It raises ValueError because "10" is a string, not an int, and the total stays unchanged.
Your progress
Reveal the check answer or reach the end to complete this lesson.