Classes and objects
A class is a blueprint for creating objects. An object bundles data (attributes) with the functions that operate on that data (methods). Almost everything in Python is an object, including numbers, strings and functions.
Defining a class
class Dog:
pass
d = Dog()
print(type(d))Class names use PascalCase. Calling the class like a function creates an instance.
The init method
__init__ runs automatically when an instance is created. It is where you set up the object's attributes.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
buddy = Dog("Buddy", 3)
print(buddy.name, buddy.age)self is the instance being created. Python passes it automatically as the first argument to every method; you never pass it yourself.
Methods
Functions defined inside a class. They always take self first so they can reach the instance's attributes.
class Dog:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} says woof"
def rename(self, new_name):
self.name = new_name
d = Dog("Rex")
print(d.speak())
d.rename("Max")
print(d.speak())Attributes can be changed
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
return "Insufficient funds"
self.balance -= amount
return self.balance
acc = Account("Meena", 500)
acc.deposit(250)
print(acc.withdraw(100))
print(acc.withdraw(5000))
print(acc.balance)Class attributes
Defined directly in the class body, shared by every instance.
class Dog:
species = "Canis familiaris"
def __init__(self, name):
self.name = name
a = Dog("A")
b = Dog("B")
print(a.species, b.species)
Dog.species = "dog"
print(a.species)Use them for constants and defaults. Be careful with mutable class attributes like lists; they are shared too.
str for printing
By default printing an object shows something unhelpful. Define __str__ to control it.
class Dog:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Dog named {self.name}"
print(Dog("Bruno"))More special methods are covered in the special methods lesson.
Objects in collections
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
roster = [Student("Ali", 82), Student("Bela", 91), Student("Chen", 77)]
best = max(roster, key=lambda s: s.marks)
print(best.name)
for s in sorted(roster, key=lambda s: s.name):
print(s.name, s.marks)Deleting
class Thing:
pass
t = Thing()
t.colour = "red" # attributes can be added later
del t.colour
del tPractice
- Write a
Rectangleclass withwidthandheightattributes and methodsarea()andperimeter(). - Add a
__str__method soprint(Rectangle(3, 4))showsRectangle 3x4. - Write a
Counterclass with anincrement()method and a class attribute that counts how manyCounterobjects have been created.
