Lecture 6 · Objects and classes

One class.
Two characters.

The class defines the rules.
Each object keeps its own state.

Optional practice. Exams are based on lecture notes.
Step 0
The blueprint

A class is not a character.

Run the walkthrough to create two separate objects from the same class.

Character objects0 objects
CLASSPlayerCharacter
player1
Object A

Grog

Not created
health· / 100
max_health
·
is_defeated
·
player2
Object B

Vex

Not created
health· / 80
max_health
·
is_defeated
·

Inside the class

Python
Current callplayer1 = PlayerCharacter("Grog", 100)
class PlayerCharacter:

          

Printed output

0 lines
Nothing printed yet

The idea to keep

Same methods.
Separate state.

player1.take_damage(30) uses the method defined by PlayerCharacter. Inside that call, self refers to the object named by player1.

The class is shared. Grog’s and Vex’s health values are not.

Make a prediction

One more method call

Start with Grog at 100 and Vex at 80. Run player2.take_damage(50). What are their health values now?

Choose Grog’s health and Vex’s health