Start free

A level · 5 exercises

Python classes

A class describes a kind of object: its data (attributes, set in __init__) and what it can do (methods). Each object made from it has its own data.

self is the object a method is called on; __str__ says how the object prints.

class Account:
    def __init__(self, owner):
        self.owner = owner
        self.balance = 0

    def pay_in(self, amount):
        self.balance += amount

acc = Account("Ann")
acc.pay_in(5)
print(acc.balance)

Watch for: Every method's first parameter is self, and attributes are reached through it: self.balance, not balance.

Exercises

  1. Bank accountWrite a class Account with deposit, withdraw and a balance.Advanced
  2. FractionsWrite a Fraction class that adds two fractions and keeps the result in lowest termsAdvanced
  3. VectorsWrite a Vector class for 2D vectors with + (addition), a dot product method and aAdvanced
  4. ShapesWrite a base class Shape with an area() method and subclasses Circle, Rectangle andAdvanced
  5. Clock arithmeticWrite a Time class holding hours and minutes, with a method that adds minutes andAdvanced
Start with “Bank account”