单继承语法: 一个子类继承一个父类
class 类名(父类名):
类内容体
多继承语法: 一个子类继承多个父类------优先级:从左到右
class 类名(父类名1,父类名2,父类名2....父类名n):
类内容体
复写:子类复写父类成员方法,在子类中重新定义同名的属性或方法
子类中调用父类同名成员: 一旦复写父类成员,那么类对象调用成员的时候,就会调用复写后的新成员,如果需要使用被复写的父类的成员,就需要特殊的调用方式:
方式一:调用父类成员
使用成员变量:父类名.成员变量
使用成员方法:父类名.成员方法(self)
方式二:使用super()调用父类成员
使用成员变量:super().成员变量
使用成员方法:super().成员方法()
单继承例子:
- # 单继承
- class Phone:
- IMEI = None
- producter = "HH"
-
- def call_by_4g(self):
- print("4g")
-
-
- class SonPhone(Phone):
- face_id = "001"
-
- def call_by_5g(self):
- print("5g")
-
-
- sonphone = SonPhone()
- print(sonphone.producter)
- sonphone.call_by_4g()
- sonphone.call_by_5g()
多继承例子:
- # 多继承
- class Phone:
- IMEI = None
- producter = "HH"
-
- def call_by_4g(self):
- print("4g")
-
-
- class NFCReader:
- nfc_type = "第五代"
- producter = "hh"
-
- def read_card(self):
- print("NFC读卡")
-
- def write_card(self):
- print("NFC写卡")
-
-
- class RemoteControl:
- rc_type = "红外遥控"
-
- def control(self):
- print("红外遥控")
-
-
- class SonPhone(Phone, NFCReader, RemoteControl):
- pass # 语法补全不报错
-
- # face_id = "001"
- #
- # def call_by_5g(self):
- # print("5g")
-
-
- sonphone = SonPhone()
- print(sonphone.producter) # Phone中的 优先级:从左到右
- sonphone.call_by_4g()
- sonphone.read_card()
- sonphone.write_card()
- sonphone.control()
复写例子:
- # 复写---复写父类成员
- class Phone:
- IMEI = None
- producter = "HH" # 复写成员变量
-
- def call_by_4g(self): # 复写成员方法
- print("4g")
-
-
- class SonPhone(Phone):
- producter = "MM"
- face_id = "001"
-
- def call_by_4g(self):
- print("复写")
-
-
- sonphone = SonPhone()
- print(sonphone.producter)
- sonphone.call_by_4g()
复写父类成员:
- # 复写父类成员
- class Phone:
- IMEI = None
- producter = "HH"
-
- def call_by_4g(self):
- print("4g")
-
-
- class SonPhone(Phone):
- producter = "MM"
- face_id = "001"
-
- def call_by_4g(self):
- print("复写")
- print("5g")
- print("啦啦啦")
-
- # 方式一:调用父类成员
- # print(Phone.producter) # HH
- # Phone.call_by_4g(self) # 4g
-
- # 方式二: 使用super()
- print(super().producter) # HH
- super().call_by_4g() # 4g
-
-
- sonphone = SonPhone()
- print(sonphone.producter) # MM
- sonphone.call_by_4g()