Ravindra Bagale · Data Scienceसर्व coursesया course चे lessonsशोधाEnglish

Data Science · मराठी आवृत्ती · Python basics

P11.4 Python Inheritance चा पाया उदाहरणासह

By Ravindra Bagale

हे का शिकायचं?

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
Pythonclass Account: def __init__(self, holder): ...
Javaclass Account { Account(String holder) { ... } }
JavaScriptclass Account { constructor(holder) { ... } }
Gotype 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 जोडली.