欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

Python2和Python3中@abstractmethod使用方法

时间:2021-08-09 08:51:54|栏目:Python代码|点击:

这篇文章主要介绍了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 PyQt5 爬虫实现代码

栏    目:Python代码

下一篇:Python 获得命令行参数的方法(推荐)

本文标题:Python2和Python3中@abstractmethod使用方法

本文地址:http://www.codeinn.net/misctech/165545.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有