Python2和Python3中@abstractmethod使用方法
2020-02-13 11:30
781 查看
这篇文章主要介绍了Python2和Python3中@abstractmethod使用方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
抽象方法:
抽象方法表示基类的一个方法,没有实现,所以基类不能实例化,子类实现了该抽象方法才能被实例化。
Python的abc提供了@abstractmethod装饰器实现抽象方法,下面以Python3的abc模块举例。
@abstractmethod:
基类Foo的fun方法被@abstractmethod装饰了,所以Foo不能被实例化;子类SubA没有实现基类的fun方法也不能被实例化;子类SubB实现了基类的抽象方法fun所以能实例化。
完整代码:
在Python3.4中,声明抽象基类最简单的方式是子类话abc.ABC;Python3.0到Python3.3,必须在class语句中使用metaclass=ABCMeta;Python2中使用__metaclass__=ABCMeta
Python3.4 实现方法:
from abc import ABC, abstractmethod class Foo(ABC): @abstractmethod def fun(self): '''please Implemente in subclass''' class SubFoo(Foo): def fun(self): print('fun in SubFoo') a = SubFoo() a.fun()
Python3.0到Python3.3的实现方法:
from abc import abstractmethod, ABCMeta class Bar(metaclass=ABCMeta): @abstractmethod def fun(self): '''please Implemente in subclass''' class SubBar(Bar): def fun(self): print('fun in SubBar') b = SubBar() b.fun()
Python2的实现方法:
from abc import ABCMeta, abstractmethod class FooBar(): __metaclass__ = ABCMeta @abstractmethod def fun(self): '''please Implemente in subclass''' class SubFooBar(FooBar): def fun(self): print('fun in SubFooBar') a = SubFooBar() a.fun()
以上就是本文的全部内容,希望对大家的学习有所帮助
您可能感兴趣的文章:
相关文章推荐
- Python __getattr__与__setattr__使用方法
- Python httplib,smtplib使用方法
- python中做层次聚类,使用scipy.cluster.hierarchy.fclusterdata方法 - Waleking的专栏 - 博客频道 - CSDN.NET
- python下使用qrcode方法
- fedora 15 升级python后yum无法使用的解决方法
- Python Matplotlib安装方法以及使用
- 在python中使用cx_Oracle模块出现“DLL Load failed”的处理方法
- Python httplib,smtplib使用方法
- Python中使用中文的方法
- 【转】python直接生成exe的方法(使用py2exe)
- Python中的strip()和lstrip()以及rstrip()方法的使用
- python join 和 split的常用使用方法
- Python基本使用方法记录
- python 各种解析xml包使用方法总结 - 转
- Python 模块paramiko简单使用方法
- Python __getattr__与__setattr__使用方法
- python中datetime的比较方法使用
- 使用python获取本地时区的几种方法
- python多文件使用同一个全局变量的定义和使用方法
- Python 正则表达式 RE模块的使用方法