Kids Coding
A First Class
A class groups data and actions. Make a Player with a name and a score.
A stamp for many objects
A class is a template. An object is one instance: it has its own data. self means this object.
A Player
class Player:
def __init__(self, name):
self.name = name
self.score = 0
def add(self, points):
self.score = self.score + points
sam = Player("Sam")
sam.add(10)
print(sam.name, sam.score)A class is a cookie cutter; each object you make from it is a cookie. One cutter, many cookies, all the same shape.
Two players, two scores
Separate boxes
class Player:
def __init__(self, name):
self.name = name
self.score = 0
def add(self, points):
self.score = self.score + points
a = Player("Sam")
b = Player("Riley")
a.add(5)
b.add(12)
print(a.name, a.score)
print(b.name, b.score)Real life
Two players on the same football pitch, each with their own score.
Same template (Player). Two objects. Sam’s goals do not add to Riley’s.
Match sheet
class Player:
def __init__(self, name):
self.name = name
self.goals = 0
def score(self):
self.goals = self.goals + 1
sam = Player("Sam")
riley = Player("Riley")
sam.score()
sam.score()
riley.score()
print(sam.name, sam.goals)
print(riley.name, riley.goals)Change one word. Run it. That is how this idea shows up outside the lesson.
Try it
Exercise 1: Make a Book class with title. Create one book and print its title.
Show solution
class Book:
def __init__(self, title):
self.title = title
book = Book("Foxes")
print(book.title)