Reputation: 35
this is the code.
class MyPet:
dogs = []
def __init__(self, dogs):
self.dogs = dogs
class MyDog:
species = 'mammal' # Class Attribute
def __init__(self, name, age): # Initializer / Instance attributes
self.name = name
self.age = age
def description(self): # Instance Method 1
return self.name, self.age
def speak(self, sound): # Instance Method 2
return "%s says %s" % (self.name, sound)
def eat(self): # Instance Method 3
self.is_hungry = False
class Bulldog(MyDog):
def run(self, speed):
return "%s runs %s" % (self.name, speed)
class RussellTerrier(MyDog):
def run(self, speed):
return "%s runs %s" % (self.name, speed)
class SiberianHusky(MyDog):
def run(self, speed):
return "%s runs %s" % (self.name, speed)
The output should be like this:
These are my 3 dogs namely:
Justin runs at the speed of 5.
Drake runs at the speed of 6.
Kanye runs at the speed of 7.
Upvotes: 0
Views: 65
Reputation: 436
We have 2 parent classes MyDog
and MyPet
.
Let's focus on MyDog
The code given is:
class MyDog:
species = 'mammal' # Class Attribute
def __init__(self, name, age): # Initializer / Instance attributes
self.name = name
self.age = age
def description(self): # Instance Method 1
return self.name, self.age
def speak(self, sound): # Instance Method 2
return "%s says %s" % (self.name, sound)
def eat(self): # Instance Method 3
self.is_hungry = False
Now let's take one sub-class (BullDog)
class BullDog(MyDog):
def run(self, speed):
return "%s runs %s" % (self.name, speed)
If we initialize a new BullDog
(i.e.
bd = BullDog(name, age)
Now bd
has all the properties of MyDog
as well as run
. So we can say bd.eat(); bd.speak("bark");
so on and so forth.
If you want to learn more about inheritance feel free to ask in the comments/read this doc: https://www.python-course.eu/python3_inheritance.php
Upvotes: 1