Chapter 13

Classes and Objects

A class is how you define your own kind of object, one that keeps related data and behavior in the same place.

Chapter 13, Classes and Objects

What you will learn

  • Understand class, object, attribute, and method.
  • Use __init__() to initialize an object.
  • Understand self at a practical level.
  • Build a small class without diving into advanced OOP theory.

The code from this chapter

Type these programs yourself. The predictions below are the exercises; the explanations are in the book.

13.2 Your First Class

TPRM Lab 13.2: Create a Player

Type this into a file, predict the output, then run it.

Python
class Player:
    def __init__(self, name, score=0):
        self.name = name
        self.score = score

    def add_points(self, points):
        self.score += points

player1 = Player("Alex")
player1.add_points(10)
player1.add_points(5)

print(player1.name)
print(player1.score)

13.3 __init__ Sets the Starting State

Type this into a file, predict the output, then run it.

Python
class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    def sale_price(self, percent_off):
        return self.price * (1 - percent_off / 100)

book = Product("Python the TPRM Way", 19.99)
print(f"{book.sale_price(20):.2f}")

Back to Python the TPRM Way