Data Science · मराठी आवृत्ती · Python basics
P11.4 Python Inheritance चा पाया उदाहरणासह
हे का शिकायचं?
Savings account हा account च आहे, फक्त interest जास्त. सगळं पुन्हा लिहायची गरज नाही.
हे काय आहे?
class Child(Parent): parent च्या सगळ्या methods घेतो आणि नवीन जोडू शकतो. super() parent चा code चालवतो.
कसं करायचं?
Step 1. class Child(Parent): लिहा.
Step 2. super().__init__() call करा.
Step 3. नवीन method जोडा.
Python आणि इतर भाषा: तुलना
या भाषा शिकायची गरज नाही. Python किती सोपा वाचायला आहे ते दाखवण्यासाठी ही table आहे.
| भाषा | 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) |
उदाहरणं: copy करा आणि चालवा
उदाहरण A: Savings account
हा 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)
तुम्हाला दिसणारा output:
1545.0
याचा अर्थ: Child class ने parent चे methods वापरले आणि interest ची नवीन method जोडली.