A class describes a kind of object: what it stores and what it can do. __init__ runs when an object is created and sets its attributes on self; other methods take self first too, and that is how they reach the object's data. c = Counter() creates an instance; c.increment() calls a method on it, Python filling in self.
Class names are written in CapWords. Every instance has its own attributes, so two counters count separately. Methods that change the object often also return the new state, which makes them convenient to use in expressions.
class Account:
def __init__(self, owner):
self.owner = owner
self.balance = 0
def deposit(self, amount):
self.balance += amount
return self.balance
a = Account("Ada")
a.deposit(50)
print(a.owner, a.balance) # Ada 50Your task
Write class Counter whose count starts at 0, with increment() that adds one and returns the new count, and reset() that sets it back to 0. Then write class Report created with a list of words: it stores the list as words and sets total (how many words) and unique (how many different words), and its summary() method returns "<total> words, <unique> unique".
Part of the final project. Report holds the numbers the project computes and prints the summary line. It is saved in this browser and loaded into Project: text statistics when you get there.
Hint 1
def __init__(self): self.count = 0
Hint 2
In Report.__init__: self.words = words; self.total = len(words); self.unique = len(set(words)). summary returns an f-string.
Show the solution
class Counter:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
return self.count
def reset(self):
self.count = 0
class Report:
def __init__(self, words):
self.words = words
self.total = len(words)
self.unique = len(set(words))
def summary(self):
return f"{self.total} words, {self.unique} unique"