简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM