Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: Can't instantiate abstract class <...> with abstract methods

Here is my code:

from abc import ABC
from abc import abstractmethod

class Mamifiero(ABC):
    """docstring for Mamifiero"""
    def __init__(self):
        self.alimentacion = 'carnivoro'
    
    @abstractmethod
    def __respirar(self):
        print('inhalar... exhalar')
    
class Perro(Mamifiero):
    """docstring for Perro"""
    def __init__(self, ojos=2,):
        self.ojos = ojos

I want that perro.respirar() prints 'inhalar... exhalar' but when I want to instantiate a Perro class show me this error. I want to know what is wrong with my script

like image 349
Vinsmoke Mau Avatar asked Sep 02 '25 07:09

Vinsmoke Mau


1 Answers

By definition (read the docs), an abstract call is a class which CANNOT be instantiated until it has any abstract methods not overridden. So as in the Object-Oriented Programming by design.

You have an abstract method Perro.__respirar() not overridden, as inherited from the parent class. Or, override it with a method Perro.__respirar(), and do something there (maybe even call the parent's method; but not in case it is private with double-underscore, of course).

If you want to instantiate Perro, just do not make that method abstract. Make it normal. Because it also has some implementation, which suggests it is a normal base-class'es method, not an abstract method.

like image 126
Sergey Vasilyev Avatar answered Sep 04 '25 19:09

Sergey Vasilyev