【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 @ 2021-11-05 11:01  淡怀  阅读(2645)  评论(0编辑  收藏  举报