Skip to main content

Unit 6 · Class is in Session · Lesson 49 of 57

Changing State

Changing state

Methods can do more than give back answers. They can also change the object they belong to.

class Counter:
    def __init__(self):
        self.count = 0

    def click(self):
        self.count += 1

clicker = Counter()
clicker.click()
clicker.click()
print(clicker.count)
2

self.count += 1 changes the count stored on that object, and it stays changed. The object remembers.

Every object remembers its own stuff

karls_clicker = Counter()
alexs_clicker = Counter()

alexs_clicker.click()
alexs_clicker.click()
alexs_clicker.click()

print(karls_clicker.count)
print(alexs_clicker.count)
0
3

They're built from the same blueprint, but each one has its own count. Alex clicking his doesn't touch mine. Two houses built from the same blueprint don't share furniture!

The data an object is holding right now is called its state.

Let's model the CyberAcad website. Alex will be thrilled.

Make a class called Website:

  • __init__ takes a name, stores it, and also starts self.deleted as False and self.times_deleted as 0
  • a method called delete sets deleted to True, and adds 1 to times_deleted
  • a method called restore sets deleted back to False (but times_deleted stays, we're keeping track)

Python exercise

Write the program in an editor next to the lesson, run it, and have it checked automatically. Create a free account to do this part.

Do this lesson for real

With a free account you get the terminals, challenges and checks that go with the lessons in Intro to Python, and your progress is saved as you go. CyberAcad is a 501(c)(3) nonprofit, so there is nothing to pay.