【Python】接口定义及实现

 

 

 

 

 

 

一、无返回值

复制代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
@Time    :
@Author  :
@File    :
@Version :1.0
@Function:
"""


# 定义接口
class InterfaceRoot(object):
    def get_a(self):
        pass

    def get_b(self):
        pass

    def get_c(self):
        pass


# 接口实现1
class Impl1InterfaceRoot(InterfaceRoot):
    def get_a(self):
        print("Impl1_a")

    def get_b(self):
        print("Impl1_b")


# 接口实现2
class Impl2InterfaceRoot(InterfaceRoot):
    def get_a(self):
        print("Impl2_a")

    def get_b(self):
        print("Impl2_b")

    def get_c(self):
        print("Impl2_c")


if __name__ == '__main__':
    print('Impl1InterfaceRoot 实现')
    Impl1InterfaceRoot().get_a()
    Impl1InterfaceRoot().get_b()
    Impl1InterfaceRoot().get_c()
    print('Impl2InterfaceRoot 实现')
    Impl2InterfaceRoot().get_a()
    Impl2InterfaceRoot().get_b()
    Impl2InterfaceRoot().get_c()
复制代码

输出

Impl1InterfaceRoot 实现
Impl1_a
Impl1_b
Impl2InterfaceRoot 实现
Impl2_a
Impl2_b
Impl2_c

 

二、有返回值

 -> 后面表示说明此方法的返回值(注释作用)

 ... 表示返回值可以有0个或多个

复制代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
@Time    :
@Author  :
@File    :
@Version :1.0
@Function:
"""


# 定义接口
class InterfaceRoot(object):
    def get_a(self) -> int: ...

    def get_b(self) -> int: ...

    def get_c(self) -> int: ...


# 接口实现1
class Impl1InterfaceRoot(InterfaceRoot):
    def get_a(self):
        print("Impl1_a")
        return '接口实现1 get_a 返回值'

    def get_b(self):
        print("Impl1_b")


# 接口实现2
class Impl2InterfaceRoot(InterfaceRoot):
    def get_a(self):
        print("Impl2_a")

    def get_b(self):
        print("Impl2_b")

    def get_c(self):
        print("Impl2_c")


if __name__ == '__main__':
    print('---------------------------------------Impl1InterfaceRoot 实现')
    print(Impl1InterfaceRoot().get_a())
    Impl1InterfaceRoot().get_b()
    Impl1InterfaceRoot().get_c()
    print('---------------------------------------Impl2InterfaceRoot 实现')
    print(Impl2InterfaceRoot().get_a())
    Impl2InterfaceRoot().get_b()
    Impl2InterfaceRoot().get_c()
复制代码

输出:

---------------------------------------Impl1InterfaceRoot 实现
Impl1_a
接口实现1 get_a 返回值
Impl1_b
---------------------------------------Impl2InterfaceRoot 实现
Impl2_a
None
Impl2_b
Impl2_c

posted @   淡怀  阅读(2666)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义

目录导航

点击右上角即可分享
微信分享提示