1

When I run this Python program, dog.bark() returns "This dog is barking" but dog.eat() returns "This animal is eating".

I need dog.eat() to also return "This dog is eating" using a variable similarly to this:

class Animal(Organism):

    def eat(self):

        print("This ***{self}*** is eating")

This would allow other animals to also return their own name instead of "animal". E.g "This turtle is eating, this squirrel is eating, etc.

Obviously {self} is not the right syntax, that's why I'm looking for answers or resources regarding what I'm trying to do. If you could reply or redirect me that would be super nice.

class Organism:

    alive = True

class Animal(Organism):

    def eat(self):
        print("This animal is eating")

class Dog(Animal):

    def bark(self):
        print("This dog is barking")

dog = Dog()
dog.eat()
dog.bark()

Jamiu S.
  • 5,257
  • 5
  • 12
  • 34

1 Answers1

0

Add a name() function that you override in each subclass, then call that to generate the output string:

class Animal(Organism):

    def name(self):
        return "animal"

    def eat(self):
        print(f"This {self.name()} is eating")

class Dog(Animal):

    def name(self):
        return "dog"

    def bark(self):
        print("This dog is barking")

Even simpler, but less flexible, is to make the name a class attribute instead:

class Animal(Organism):

    NAME = "animal"

    def eat(self):
        print(f"This {self.NAME} is eating")

class Dog(Animal):

    NAME = "dog"

    def bark(self):
        print("This dog is barking")
Thomas
  • 174,939
  • 50
  • 355
  • 478
  • No real reason to make `name` a method instead of a simple class attribute… Also sounds like OP just wants to use the already existing class name. – deceze Aug 17 '22 at 11:42
  • I would not use the class name directly. If I rename the class during refactoring, I would want the output of the program to stay the same. And what about animals like the `BaldEagle`? You wouldn't want to turn that into `baldeagle`. – Thomas Aug 17 '22 at 11:47
  • That's up to OP to decide. You _could_ apply intelligent CamelCase to lower case formatting if you needed it. — As for your edit: using an attribute is also hardly "less flexible", you can replace it with a `@property` at any time if you need it to do more than just being a plain value. – deceze Aug 17 '22 at 11:48