python import 类 继承_python:类的继承

今天是阅读同事写的代码的时候,看到在实现中他使用了类的继承的方式,想起来还没有编写过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)

运行以上代码的输出结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值