No error while instantiating abstract class, even though abstract method is not implemented

冷暖自知 提交于 2019-12-11 03:04:55

问题


I was trying out the below python code:

from abc import ABCMeta, abstractmethod

class Bar:

    __metaclass__ = ABCMeta

    @abstractmethod
    def foo(self):
        pass


class Bar2(Bar):
    def foo2(self):
        print("Foo2")


b = Bar()
b2 = Bar2()

I thought having @abstractmethod will ensure that my parent class will be abstract and the child class would also be abstract as it is not implementing the abstract method. But here, I get no error trying to instantiate both the classes.

Can anyone explain why?


回答1:


You must set meta-class of Bar class to ABCMeta.

Python 2:

class Bar:
    __metaclass__ = ABCMeta

    @abstractmethod
    def foo(self):
        pass

Python 3:

class Bar(object, metaclass=ABCMeta):
    @abstractmethod
    def foo(self):
        pass


来源:https://stackoverflow.com/questions/28688784/no-error-while-instantiating-abstract-class-even-though-abstract-method-is-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!