LevelJar Sign in

Python course / Working Python

Classes and objects

Keep data and the code that looks after it in one place, in classes that cannot be put into a broken state. Inheritance that reads perfectly in words and falls apart in code is the classic mistake here.

  • __init__ and self
  • methods
  • repr
  • equality
  • inheritance
  • composition
  • properties
  • one way in

Start this module

Runs in your browser. Start straight away; create an account when you want your progress kept.

state, behaviour and a readable repr
class Jar:
    def __init__(self, contents, grams):
        self.contents = contents
        self.grams = grams

    def __repr__(self):
        return f"Jar({self.contents!r}, {self.grams})"

    @property
    def is_empty(self):
        return self.grams == 0

    def take(self, grams):
        self.grams = max(0, self.grams - grams)


jar = Jar("honey", 340)
jar.take(340)
print(jar, "empty:", jar.is_empty)
Jar('honey', 0) empty: True

What you will learn

The lessons in this module

  • What a class is for
  • __init__ and self
  • Methods
  • Shared by the class, or owned by the instance
  • Showing an object
  • When two objects are equal
  • Inheriting
  • super()
  • Overriding
  • When inheritance is wrong
  • Having, rather than being
  • Duck typing
  • Properties
  • Getters that do nothing
  • What the underscore means
  • Another way to make one
  • Static methods
  • One way in
  • Putting objects in order
  • How big, and is it anything
  • in, and looking things up
  • Objects that add up
  • Copying an object
  • Objects and dictionaries
  • A model over a file
  • Saving the model
  • Errors that carry facts
  • Which line was it
  • A flag that wants to be classes
  • A class that does too much
  • The stock room
  • Module review: the tool library

Ready when you are

Start this module

Previous: Files and the filesystem. Next: Modules and imports. All modules are on the course page.