今天是阅读同事写的代码的时候,看到在实现中他使用了类的继承的方式,想起来还没有编写过python中类的继承。
阅读了一些文章,文章参考:https://www.cnblogs.com/bigberg/p/7182741.html
稍微写了一点儿程序操作下:
from enum import IntEnum
class DeviceType(IntEnum):
UNKNOWN = 0
EARBUD = 1
CASE = 2
SUPERCASE = 3
DEBUG_BOARD = 4
def __int__(self):
return self.value
class Device(object): #这是基类
def __init__(self, port, name, device_type=DeviceType.UNKNOWN):
self.port = port #基类具有的一些属性,继承于这个Device的子类都有这些属性
self.name = name
self.device_type = device_type
print("the device type is {}".format(DeviceType(self.device_type)))
def send_cli_command(self): #这是基类的一些方法
print("send cmd")
pass
def connect(self):
print("connect port")
pass
def disconnect(self):
print("disconnect port")
pass
class Buds(Device): #Buds子类继承了Device类。
def __init__(self,port,name): #这是构造函数的继承,因为在实例类的时候子类有参数需要传递,因此重写构造函数,首先是继承,然后是重写
Device.__init__(self,port,name,device_type=DeviceType.EARBUD) #这边是重写了Device类中的构造函数,传入了不同的参数
pass
class Cases(Device):#Cases子类继承了Device类。
def __init__(self,port,name):
Device.__init__(self,port,name,device_type=DeviceType.CASE)#这个子类和Buds子类的DeviceType类别有区别所以有不同的重写参数需要传递
pass
port1=123
name1="device1"
port2=134
name2="device2"
bud = Buds(port1,name1)
case=Cases(port2,name2)
运行以上代码的输出结果: