zoukankan      html  css  js  c++  java
  • @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://blog.csdn.net/xiemanR/article/details/72629164

  • 相关阅读:
    大数加法、乘法实现的简单版本
    hdu 4027 Can you answer these queries?
    zoj 1610 Count the Colors
    2018 徐州赛区网赛 G. Trace
    1495 中国好区间 尺取法
    LA 3938 动态最大连续区间 线段树
    51nod 1275 连续子段的差异
    caioj 1172 poj 2823 单调队列过渡题
    数据结构和算法题
    一个通用分页类
  • 原文地址:https://www.cnblogs.com/idontknowthisperson/p/10090012.html
Copyright © 2011-2022 走看看