Object-Oriented Python
Harry
· 14 Sep 2026
· 1 views
Advertisement
Classes and Objects
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def describe(self):
return f"{self.title} by {self.author}"
b = Book("The Alchemist", "Paulo Coelho")
print(b.describe())Attributes and Methods
__init__is the constructor that sets up each new object.selfrefers to the current instance.- Methods use the same syntax as functions but always take
selffirst.
Inheritance
class Ebook(Book):
def __init__(self, title, author, page_count):
super().__init__(title, author)
self.page_count = page_count
def describe(self):
return f"{super().describe()} - {self.page_count} pages"
e = Ebook("Deep Work", "Cal Newport", 304)
print(e.describe())Encapsulation
class Account:
def __init__(self, owner, balance=0):
self.owner = owner
self._balance = balance # protected by convention
def deposit(self, amount):
self._balance += amount
@property
def balance(self):
return self._balance
acc = Account("Priya", 1000)
acc.deposit(500)
print(acc.balance)Python uses _name (protected) and __name (name-mangled) by convention rather than enforced private fields.
Key Points
class+__init__define objects; methods always takeself.- Inheritance with
super()re-uses and customises parent behaviour. @propertycreates computed, read-friendly attributes.