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

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

问题描述

我正在尝试以下 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()

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

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 类的 meta-class 设置为 ABCMeta.

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

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

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