Python Inheritance
In this page:
class ParentClass:
# parent members
class ChildClass(ParentClass):
# child members
# super().method_name() calls the parent
Inheritance क्या है?
Inheritance किसी child class को parent class के attributes और methods अपने-आप पाने देता है, इसलिए common behavior (जैसे एक general Animal.eat() method) सिर्फ एक बार लिखनी होती है और हर subclass (Dog, Cat) को वह free में मिल जाती है।
उदाहरण: What is Inheritance?
class Animal:
def eat(self):
print("Eating")
class Dog(Animal): # Dog inherits eat() from Animal
pass
Dog().eat()
एक Subclass बनाना
class Dog(Animal): लिखना Dog को Animal का subclass बना देता है — Animal द्वारा define हर method और attribute तुरंत Dog instances पर उपलब्ध हो जाता है, यहाँ तक कि आपके Dog के अपने body में कुछ जोड़ने से पहले भी।
उदाहरण: Creating a Subclass
class Animal:
def eat(self):
print("Eating")
class Dog(Animal): # subclass of Animal
def bark(self):
print("Woof")
d = Dog()
d.eat() # inherited from Animal
d.bark() # defined directly on Dog
Method Overriding
अगर कोई child class अपने parent में मौजूद method जैसे ही नाम वाला method define करती है, तो child instance पर उस method को call करने पर child का version ही चलता है — subclasses parent class को छुए बिना inherited behavior को इसी तरह customize करती हैं।
उदाहरण: Method Overriding
class Animal:
def speak(self):
print("Some sound")
class Dog(Animal):
def speak(self): # overrides Animal's speak method
print("Woof")
Dog().speak() # runs Dog's version, not Animal's
super() Function
super() किसी child class को अपने parent तक वापस पहुँच देता है, जिसे सबसे ज़्यादा __init__ के अंदर super().__init__(...) के रूप में इस्तेमाल किया जाता है ताकि child के अपने attributes जोड़ने से पहले parent का setup logic चले, जिससे parent के initialization code को duplicate न करना पड़े।
उदाहरण: The super() Function
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # runs Animal's __init__ to set self.name
self.breed = breed
d = Dog("Rex", "Labrador")
print(d.name, d.breed)
Multiple Inheritance
एक ही class एक से ज़्यादा parents list कर सकती है — class Duck(Swimmer, Flyer): — दोनों से inherit करते हुए, जो independent capabilities को combine करने के लिए powerful है पर जब वे parents overlapping method names define करते हैं तो method resolution order समझना ज़रूरी हो जाता है।
उदाहरण: Multiple Inheritance
class Swimmer:
def swim(self):
print("Swimming")
class Flyer:
def fly(self):
print("Flying")
class Duck(Swimmer, Flyer): # inherits from both parent classes
pass
d = Duck()
d.swim()
d.fly()
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: