python inheritance
This commit is contained in:
31
src/advance/inheritance.py
Normal file
31
src/advance/inheritance.py
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
# Single Inheritance
|
||||||
|
class Animal:
|
||||||
|
def __init__(self, name):
|
||||||
|
self.name = name
|
||||||
|
|
||||||
|
def make_sound(self):
|
||||||
|
print(f"{self.name} makes a sound")
|
||||||
|
|
||||||
|
def move_forward(self):
|
||||||
|
print(f"{self.name} moveing forward.... super class")
|
||||||
|
|
||||||
|
|
||||||
|
class Dog(Animal):
|
||||||
|
|
||||||
|
def __init__(self, name, age):
|
||||||
|
super().__init__(name) # call Animal's __init__
|
||||||
|
self.age = age
|
||||||
|
|
||||||
|
def bark(self):
|
||||||
|
print(f"{self.name} says Bark!") # name is super class arrtibute
|
||||||
|
|
||||||
|
|
||||||
|
# If child defines the same variable, it overrides the parent’s version.
|
||||||
|
|
||||||
|
def move_forward(self): # method overriding
|
||||||
|
print(f"{self.name}, ({self.age}) moveing forward.... child class")
|
||||||
|
|
||||||
|
|
||||||
|
dog = Dog("Tommy", 2)
|
||||||
|
dog.bark()
|
||||||
|
dog.move_forward()
|
||||||
Reference in New Issue
Block a user