Monday 7 December 2020

Part Four: Example 3: class Inheritance

 We can create a class that would have all the common attributes then create subclasses that would have peculiar attributes in addition to the common attributes in the main class.

Example is the class Mammal below. The main class has the attribute walk which is common to the Mammal class. 
However, in the subclass Dog there is the peculiar attribute bark in addition to the common attribute walk.
Also, in the subclass Cat there is the peculiar attribute meow in addition to the common attribute walk.
 
The code is given below:
 
 

class Mammal:
   def walk(self):
      print('walk')

class Dog(Mammal):
   def bark(self):
      print('bark')

class Cat(Mammal):
   def meow(self):
      print('meowing')

dog1 = Dog()
dog1.walk()

cat1 = Cat()
cat1.meow()

When we run the code we have the following output:

 
walk
meowing 

No comments:

Post a Comment