Line At A Time
Lesson 6: A Team of Objects
A Team of Objects Combine classes with lists and loops.
1class Player:
2 def __init__(self, name, score):
3 self.name = name
4 self.score = score
5
6 def cheer(self):
7 print(f"Go {self.name}! Score: {self.score}")
8
9ada = Player("Ada", 100)
10grace = Player("Grace", 120)
11players = [ada, grace]
12for player in players:
13 player.cheer()
Terminal
$ python3 main.py
Go Ada! Score: 100
Go Grace! Score: 120
Every line, explained
class Player:
class Dog: defines a class: a blueprint describing what every Dog can do. Like if and def, the line ends with a colon and everything belonging to the class is indented underneath. This blueprint is for game players.
def __init__(self, name, score):
The __init__ method (two underscores each side, "dunder init") is special: Python runs it AUTOMATICALLY whenever a new object is built. It is where you fill in the object's starting values.
self.name = name
This player's name.
self.score = score
This player's score.
def cheer(self):
Something every Player can do.
print(f"Go {self.name}! Score: {self.score}")
Uses both of this player's stored values.
ada = Player("Ada", 100)
One player...
grace = Player("Grace", 120)
...and another.
players = [ada, grace]
Objects can go in a list, just like numbers or strings!
for player in players:
And a for loop can visit each object in turn: everything from Intro to Python works with your own classes.
player.cheer()
Each player cheers with their own name and score. You just combined classes, lists and loops: that is real object-oriented Python!