• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

jwang106


脚踏实地,日拱一卒。 建立新的神经链接,可不像公园散步那样简单。
  • 博客园
  • 联系
  • 管理

View Post

python 使用abc实现接口类/虚类(2.2)



python 使用abc实现接口类/虚类

具体类

class BaseA:
    def run(self):
        print('base A running')
        
class ChildA(BaseA):
    def run(self):
        print('child a')

# 具体类可以直接继承也可以实现多态
a = BaseA()
a.run()
a = ChildA()
a.run()

虚类

class BaseB():
    @abc.abstractmethod
    def run(self):
        return NotImplemented
        
    def hello(self):
        print('hello')
        
# 直接实例化不会会报错
b = BaseB() # 这里没有正确的实现虚类,正确实现看馅饼
b.run()
output: return NotImplemented

纯虚类 也就是接口类

# python2 不是继承ABC,使用 __metaclass__ = ABCMeta

class BaseE(abc.ABC):
    @abc.abstractmethod
    def run(self):
        return NotImplemented
    @abc.abstractmethod
    def hello(self):
        return print('hello')
        
class ChildE1(BaseE):
    pass
    
class ChildE2(BaseE):
    @abc.abstractmethod
    def run(self):
        print('e')
        
class ChildE3(BaseE):
    def run(self):
        print('e')
        
# e = BaseE()  报错
# e = ChildE2() 报错
e = ChildE3()
e.hello()
e.run()

继承虚类后想要改变参数类型怎么办

# 给新的参数一个默认值, 可以满足新的参数的调用
# 这样可以满足原来的参数对函数的调用,不必改变后续代码
class ChildE4(BaseE):
    def run(self, new_arg =1):
        print(new_arg)

可不可以实现 同一个函数不同的参数列表

class Test():
    def run(self):
        print('1')
    def run(self, temp):
        print(temp)
        
t = Test()
# t.run() 报错了
t.run(1)
# 所以python并没有c++里那样的virtual table去根据参数数量,去判断和使用不同的函数


posted on 2019-01-28 16:19  jwang106  阅读(1717)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3