Python2和Python3中@abstractmethod的用法
来源:互联网 发布:人工智能取代的职业 编辑:程序博客网 时间:2024/05/24 03:00
抽象方法:
抽象方法表示基类的一个方法,没有实现,所以基类不能实例化,子类实现了该抽象方法才能被实例化。
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, abstractmethodclass Foo(ABC): @abstractmethod def fun(self): '''please Implemente in subclass'''class SubFoo(Foo): def fun(self): print('fun in SubFoo')a = SubFoo()a.fun()
from abc import abstractmethod, ABCMetaclass 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()
from abc import ABCMeta, abstractmethodclass 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()
阅读全文
0 0
- Python2和Python3中@abstractmethod的用法
- python3和python2中print的用法有很多不同,python3中需要使用括号
- Anaconda中(Python2和Python3)的切换
- Anaconda中(Python2和Python3)的切换
- python2和python3中urllib的用版本区别及用法 爬虫基础
- python3.x 和 python2.x关于 urllib的用法
- python2和python3 is用法的不同,有点坑
- python3和python2的区别
- python3和python2的区别
- python2和python3的区别
- python2 和Python3的区别
- python2和python3的区别
- python2和python3的区别
- python2和python3的不同点
- Python2和Python3的区别
- python2和python3的区别
- Python2和Python3的比较
- Python2和Python3的print
- 如何在anaconda上安装pygame
- 悬浮的view在横竖屏切换时如何改变大小?
- 函数返回值—返回局部变量
- struts property输出unicode解决办法
- 前端分页例子
- Python2和Python3中@abstractmethod的用法
- Python开发简单爬虫
- Spring的三种注入方式(Setter、构造函数和自动注入)
- js常用事件
- JS操作JSON总结
- 研究:Liferay研究(二)开发Liferay中几个常用的标签
- Leetcode003. Longest Substring Without Repeating Characters
- Java时间日期格式转换
- 随系统字体放大,某个View内容显示不全问题怎么修改?