Editor

Predict the Counter Output

Beginner · Predict the output · from Python Classes and Objects: OOP from the Ground Up

From the lesson: Python Classes and Objects: OOP from the Ground Up

Imagine you own a bakery and you have a cookie cutter shaped like a star. Every time you press it into dough, you get a new star-shaped cookie. The cutter itself isn't a cookie - it's a blueprint for making cookies.

Read the lesson

Read the code carefully and predict what it prints. Think about what __init__ sets and how increment() changes self.count.

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

    def increment(self):
        self.count += 1
        return self.count

c = Counter()
print(c.increment())
print(c.increment())
print(c.increment())
# Type the exact output you predict:
class Counter:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
return self.count
c = Counter()
print(c.increment())
print(c.increment())
print(c.increment())

More Classes and Objects exercises

All Python exercises · 50 practice problems · Object-Oriented Programming quiz