Object-Oriented Python

Harry · 14 Sep 2026 · 1 views
Advertisement
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.
  • self refers to the current instance.
  • Methods use the same syntax as functions but always take self first.

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 take self.
  • Inheritance with super() re-uses and customises parent behaviour.
  • @property creates computed, read-friendly attributes.
Share this post:

Comments (0)

Please login or register to comment.