Python2和Python3中@abstractmethod使用方法

作者:邱明成 时间:2021-12-29 08:55:36 

这篇文章主要介绍了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()

来源:https://www.cnblogs.com/qiumingcheng/p/12244896.html

标签:Python,abstractmethod
0
投稿

猜你喜欢

  • 用python写一个定时提醒程序的实现代码

    2021-04-12 12:25:45
  • 详解Python 数据库 (sqlite3)应用

    2024-01-21 06:14:46
  • Vue路由应用详细讲解

    2024-05-05 09:24:03
  • Golang空接口与类型断言的实现

    2024-04-27 15:39:21
  • MySQL联合索引用法示例

    2024-01-17 08:47:16
  • Python 如何实时向文件写入数据(附代码)

    2022-11-10 13:40:03
  • Java连接MySQL数据库增删改查的通用方法(推荐)

    2024-01-22 12:00:36
  • python 计算方位角实例(根据两点的坐标计算)

    2023-08-01 09:30:54
  • python jieba分词并统计词频后输出结果到Excel和txt文档方法

    2023-10-28 21:16:37
  • 利用Python实现多种风格的照片处理

    2021-05-04 13:26:27
  • ThinkPHP 3.2 版本升级了哪些内容

    2023-09-05 04:22:04
  • ajax请求get与post的区别总结

    2024-04-29 13:58:25
  • 判断触发器正在处理的是插入,删除还是更新触发

    2024-01-19 02:03:28
  • php获取文章内容第一张图片的方法示例

    2023-11-09 18:55:14
  • 提高ASP性能的最佳选择第一部分

    2007-08-15 12:31:00
  • Python从函数参数类型引出元组实例分析

    2022-12-18 01:51:22
  • Python调用百度AI实现颜值评分功能

    2023-07-30 22:53:40
  • pytorch实现图像识别(实战)

    2022-10-03 01:19:03
  • 详解python的数字类型变量与其方法

    2023-12-05 18:40:53
  • python实现弹跳小球

    2022-05-30 08:55:08
  • asp之家 网络编程 m.aspxhome.com