[Python] abstract classes without abstract methods creating objects in python

Discussão em 'Python' iniciado por Stack, Março 4, 2025.

  1. Stack

    Stack Membro Participativo

    Basically, I knew that abstract base classes are used as skeleton classes just like regular classes, but enforces that abstract methods should be overridden by the child/inherited classes if it has one like below

    Class AbstractClass(object):
    __metaclass__ = abc.ABCMeta

    @abstractmethod
    def absmethod(self):
    pass

    class ChildClass(AbstractClass):
    def absmethod(self):
    print "Yeah!"

    obj = ChildClass()


    So we can create an object of ChildClass as above

    We know we can't instantiate an abstract class as it meant to be just skeleton and we will get an error if we try to instantiate it as below

    obj = AbstractClass()

    *** TypeError: Can't instantiate abstract class AbstractClass with abstract methods absmethod


    But what my actual query about posting this StackOverflow is if we create an abstract class by using abc.ABCMeta, without abstract methods, I can able to create an instance of the abstract class which should not be the case(correct me if I am wrong)

    Class AbstractClass(object):
    __metaclass__ = abc.ABCMeta

    obj = AbstractClass()


    OOOPPPSS it worked, we can actually create an object of abstract classes without abstract methods? So please let me know the key points behind this

    Continue reading...

Compartilhe esta Página