Reynaldo Bautista II
Reynaldo Bautista II

Reputation: 35

How can I do this? It's very confusing for me to use abstraction

this is the code.

Parent Class

class MyPet:

    dogs = []

    def __init__(self, dogs):
        self.dogs = dogs

Parent class

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

Child class (inherits from Dog class)

class Bulldog(MyDog):
    def run(self, speed):
        return "%s runs %s" % (self.name, speed)

Child class (inherits from Dog class)

class RussellTerrier(MyDog):
    def run(self, speed):
        return "%s runs %s" % (self.name, speed)

Child class (inherits from Dog class)

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

Answers (1)

gnahum
gnahum

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

Related Questions