Python Classes and Objects for Beginners: OOP Basics with Simple Examples
P11.4 Python Inheritance Basics with an Example
In short: Inheritance lets you reuse the account code and add only the new part.
Why. A savings account is an account plus interest. Inheritance lets you reuse the account code and add only the new part.
What. class Child(Parent): gets all the parent's attributes and methods. super().__init__(...) runs the parent's setup.
How.
Extend a class
- Write
class New(Old):. - In
__init__, callsuper().__init__(...). - Add new attributes and methods.
Worked example A — A savings account.
Step 1 — What we do. Savings accounts at a bank in Dublin earn interest.
Step 2 — Type and run this code.
class Account:
def __init__(self, holder, balance=0):
self.holder = holder
self.balance = balance
def deposit(self, amount):
self.balance += amount
class Savings(Account):
def __init__(self, holder, balance=0, rate=0.03):
super().__init__(holder, balance)
self.rate = rate
def add_interest(self):
self.balance += self.balance * self.rate
s = Savings("Niamh", 1000)
s.deposit(500)
s.add_interest()
print(s.balance)
Step 3 — Output you should see.
1545.0
Step 4 — What it means. deposit came from Account for free. Only add_interest is new. 1500 × 1.03 = €1545.
Python next to other languages — define a class. You do not need to learn these other languages. This only shows why Python is easier to read.
| Language | Code |
|---|---|
| Python | class Account: def __init__(self, holder): ... |
| Java | class Account { Account(String holder) { ... } } |
| JavaScript | class Account { constructor(holder) { ... } } |
| Go | type Account struct { Holder string } (no classes, uses structs) |
Ravindra Bagale's Tip
For data work, you will mostly use classes others wrote (DataFrame, Series). Knowing the basics is enough — do not over-engineer.
Ravindra Bagale's Tip – मराठी
Data work मध्ये तुम्ही बहुतेक इतरांनी लिहिलेले classes वापराल (DataFrame, Series). Basics पुरेसे — गरजेपेक्षा जास्त गुंतागुंत करू नका.
Ravindra Bagale's Tip – हिंदी
Data work में आप ज़्यादातर दूसरों के लिखे classes इस्तेमाल करोगे (DataFrame, Series). Basics काफ़ी हैं — ज़रूरत से ज़्यादा उलझाओ मत.
Samajla ka? If yes, take the quiz for this chapter. If not, run every example again and change one value each time.