CaptainAdarsh
CaptainAdarsh

Reputation: 51

How to call a method of base class with same name method in derived class in python?

code:-

class Animal():
        
    def __init__(self) -> None:
        print("Animal Created")
        
            
    def eat(self):
        print("Animal Eating")
            
class Dog(Animal):
    
    def __init__(self) -> None:
        # Animal.__init__(self)
        print ("Dog Created")
        
    def eat(self):
        print("Dog Eating")
    
mydog = Dog()
mydog.eat()

here when I call eat() method with mydog object it prints "Dog Eating", is there any way to call eat() method of base Animal class with mydog object, like is there something like this

mydog.Animal.eat() or mydog.eat(Animal)

I don't want to use super(), cause then it will call eat() from child class also so it will print both statements "Animal eating" and "Dog eating", which I doesn't want, I want to call only one at a time.

Upvotes: 4

Views: 918

Answers (1)

khelwood
khelwood

Reputation: 59096

Yes, you can call the eat method of Animal directly, passing the object as a parameter.

Animal.eat(mydog)

Though it might make for less confusing code if you give the methods different names instead.

Upvotes: 5

Related Questions