Python Classes and Objects
A class is a blueprint for a kind of thing, and an object is one thing made from that blueprint. A class Dog describes what every dog has (a name, an age) and what every dog can do (bark, eat); rex and bella are two dog objects, each with its own name and age. Classes bundle data and the functions that work on it, which keeps larger programs organised. Everything in Python is an object: strings, lists and numbers are objects of built-in classes.
Defining a class and creating objects
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return f"{self.name} says Woof!"
rex = Dog("Rex", 3)
bella = Dog("Bella", 5)
print(rex.bark())
print(bella.name, bella.age)
bella.age += 1
print(bella.age, rex.age)Rex says Woof! Bella 5 6 3
__init__ is the constructor: Python calls it automatically when you create an object with Dog("Rex", 3). Its job is to set up the new object. Values stored with self.name = ... are the object's attributes; each object has its own.
What self means
Functions defined inside a class are methods. Their first parameter, by convention called self, is the object the method is called on. rex.bark() is the same as Dog.bark(rex): Python passes rex as self, so the method can reach that object's attributes. You never pass self yourself when calling a method.
Methods that change the object
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
self.history = []
def deposit(self, amount):
self.balance += amount
self.history.append(f"+{amount}")
def withdraw(self, amount):
if amount > self.balance:
print("Not enough money")
return
self.balance -= amount
self.history.append(f"-{amount}")
acc = BankAccount("Asha", 100)
acc.deposit(50)
acc.withdraw(30)
acc.withdraw(500)
print(acc.owner, acc.balance, acc.history)Not enough money Asha 120 ['+50', '-30']
The object remembers its state between method calls: that is what makes objects useful.
Class attributes
A variable defined directly in the class body, outside any method, is a class attribute, shared by all objects of the class:
class Circle:
pi = 3.14159 # shared by every circle
count = 0
def __init__(self, r):
self.r = r
Circle.count += 1
def area(self):
return round(self.pi * self.r ** 2, 2)
c1, c2 = Circle(1), Circle(3)
print(c1.area(), c2.area(), Circle.count)3.14 28.27 2
Class names are written in CamelCase by convention: BankAccount, not bank_account.
Practice exercises
- Write a class
Studentwith a name and a list of marks, and a methodaverage. - Create three students, give them marks and print each name with the average.
- Write a class
Rectanglewith methodsareaandperimeter. - Add a class attribute that counts how many rectangles have been created.