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
- Bank accountWrite a class Account with deposit, withdraw and a balance.Advanced
- FractionsWrite a Fraction class that adds two fractions and keeps the result in lowest termsAdvanced
- VectorsWrite a Vector class for 2D vectors with + (addition), a dot product method and aAdvanced
- ShapesWrite a base class Shape with an area() method and subclasses Circle, Rectangle andAdvanced
- Clock arithmeticWrite a Time class holding hours and minutes, with a method that adds minutes andAdvanced