栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

是否可以在Python中创建抽象类?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

是否可以在Python中创建抽象类?

使用该

abc
模块创建抽象类。使用
abstractmethod
装饰器来声明方法摘要,并根据您的Python版本使用以下三种方式之一声明类摘要。

在Python
3.4及更高版本中,您可以从继承

ABC
。在Python的早期版本中,您需要将类的元类指定为
ABCmeta
。指定元类在Python
3和Python 2中具有不同的语法。三种可能性如下所示:

# Python 3.4+from abc import ABC, abstractmethodclass Abstract(ABC):    @abstractmethod    def foo(self):        pass# Python 3.0+from abc import ABCmeta, abstractmethodclass Abstract(metaclass=ABCmeta):    @abstractmethod    def foo(self):        pass# Python 2from abc import ABCmeta, abstractmethodclass Abstract:    __metaclass__ = ABCmeta    @abstractmethod    def foo(self):        pass

无论使用哪种方式,都将无法实例化具有抽象方法的抽象类,但将能够实例化提供这些方法的具体定义的子类:

>>> Abstract()Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: Can't instantiate abstract class Abstract with abstract methods foo>>> class StillAbstract(Abstract):...     pass... >>> StillAbstract()Traceback (most recent call last):  File "<stdin>", line 1, in <module>TypeError: Can't instantiate abstract class StillAbstract with abstract methods foo>>> class Concrete(Abstract):...     def foo(self):...         print('Hello, World')... >>> Concrete()<__main__.Concrete object at 0x7fc935d28898>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/612045.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号