Object-oriented programming
Classes, objects, methods, __init__ and inheritance.
All lessons · Python lessons: learn from scratch
Classes and objects
A class is a blueprint and an object is a concrete instance built from it. For example, the Account class produces a separate object for each customer. The __init__ method runs when an object is created, and self is the object itself.
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
self.balance += amount
def show(self):
print(f"{self.owner}: {self.balance} AZN")
a = Account("Rena", 50)
a.deposit(25)
a.show() # Rena: 75 AZN- Attributes hold the state of the object.
- Methods are what the object can do.
Inheritance
Inheritance lets a new class take over what an existing class offers. The subclass gets the parent's methods, may override them, or call the parent through super().
class Account:
def __init__(self, owner, balance=0):
self.owner, self.balance = owner, balance
class SavingsAccount(Account):
def __init__(self, owner, balance=0, rate=0.05):
super().__init__(owner, balance)
self.rate = rate
def add_interest(self):
self.balance *= 1 + self.rate
s = SavingsAccount("Tural", 200)
s.add_interest()
print(s.balance) # 210.0Special methods and a caution
__str__ decides how an object looks when printed, and __len__ makes it work with len(). Double underscores mark special language hooks.
class Playlist:
def __init__(self, songs):
self.songs = songs
def __len__(self):
return len(self.songs)
def __str__(self):
return "Playlist: " + ", ".join(self.songs)
p = Playlist(["A", "B"])
print(p, len(p))Advice: not everything needs to be a class. A function is enough for a simple calculation; a class pays off when state and behaviour belong together.