实例化抽象类时没有错误,即使未实现抽象方法 [英] No error while instantiating abstract class, even though abstract method is not implemented

查看:80
本文介绍了实例化抽象类时没有错误,即使未实现抽象方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以下python代码:

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()

我以为拥有 @抽象方法确保我的父类将是抽象的,子类也将是抽象的,因为它没有实现abstract方法。但是在这里,尝试实例化两个类都没有错误。

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.

谁能解释原因?

推荐答案

您必须 Bar 类的元类设置为 ABCMeta

Python 2:

class Bar:
    __metaclass__ = ABCMeta

    @abstractmethod
    def foo(self):
        pass

Python 3:

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

这篇关于实例化抽象类时没有错误,即使未实现抽象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆