Classes

Programming Languages · Python Functions & Data · 14 min

Make your own types of objects that bundle data and actions together.

A class is a blueprint

A class is a blueprint. An object is one thing built from it. Make an object by calling the class like a function:

class Robot:
    color = "silver"

bot = Robot()
print(bot.color)   # silver

The dot means "look inside": bot.color is the color that belongs to bot.

  • Define a class Dog with sound = "Woof" inside it.

  • Create a Dog object called rex and print rex.sound.

__init__ and attributes

__init__ is a special function that runs when an object is made. Use it to give each object its own data, called attributes. self means "this object".

class Robot:
    def __init__(self, name):
        self.name = name

bot = Robot("Beep")
print(bot.name)   # Beep
  • Replace pass with an __init__(self, name) that stores name in self.name.

  • Create rex = Dog("Rex") and print rex.name.

Methods

A method is a function that lives inside a class. Its first parameter is always self, so it can use the object's attributes. Call it with a dot:

class Robot:
    def __init__(self, name):
        self.name = name

    def beep(self):
        print(f"{self.name}: beep!")

Robot("Bo").beep()   # Bo: beep!
  • Add a method bark(self) that prints the dog's name followed by says Woof!.

  • Create rex = Dog("Rex") and call rex.bark().

Many objects, one class

The real power of a class: build as many objects as you like from it. Each one keeps its own attributes.

a = Robot("Beep")
b = Robot("Boop")
a.beep()   # Beep: beep!
b.beep()   # Boop: beep!
  • Create tom = Cat("Tom", 3) and kit = Cat("Kit", 1).

  • Call describe() on both cats.

Put it together: bank accounts

Build a tiny bank. Each Account has an owner and a balance that starts at 0. A deposit method adds money. Then open two accounts and put some money in.

  • Write class Account with __init__(self, owner) that stores self.owner and sets self.balance to 0.

  • Add a method deposit(self, amount) that adds amount to self.balance.

  • Make accounts for "Ada" and "Bo". Ada deposits 50 and then 25, Bo deposits 10. Print each as Ada: 75.

More in Python Functions & Data

Previous: Dictionaries · Next: Advanced OOP