python——继承

一、单继承

python——继承_第1张图片

 

# 单继承
class Phone:
    IMEI = None  # 序列号
    producer = "HM"  # 厂商

    def call_by_4g(self):
        print("4g通话")


class Phone2022(Phone):
    face_id = "10011"  # 面部识别ID

    def call_by_5g(self):
        print("2022年新功能:5g通话")

phone = Phone2022()
print(phone.producer)
phone.call_by_4g()
phone.call_by_5g()

 HM
4g通话
2022年新功能:5g通话


二、多继承 python——继承_第2张图片

# 多继承
class Phone:
    IMEI = None  # 序列号
    producer = "HM"  # 厂商

    def call_by_4g(self):
        print("4g通话")


class NFCReader:
    nfc_type = "第五代"
    producer = "Icat"

    def read_card(self):
        print("NFC读卡")

    def write_card(self):
        print("NFC写卡")


class RemoteControl:
    rc_type = "红外遥控"

    def control(self):
        print("红外遥控开启了")


class MyPhone(Phone, NFCReader, RemoteControl):
    # 补全语法,表示为空
    pass


phone = MyPhone()
phone.call_by_4g()
phone.read_card()
phone.write_card()
phone.control()

 4g通话
NFC读卡
NFC写卡
红外遥控开启了

 注意:如果多继承中父类里面有名字相同的成员,按照从左到右的顺序,显示先继承的内容。

如Phone类中的producer与NFCReader中的producer一样,但是由于在子类MyPhone的继承中,Phone在NFCReader的前面,所以print(phone.producer)的输出结果是“HM”

python——继承_第3张图片 

 

你可能感兴趣的:(python,开发语言)