在python3中所有类默认继承object,凡是继承了object的类都成为新式类,以及该子类的子类Python3中所有的类都是新式类,没有集成object类的子类成为经典类(在Python2中没有集成object的类以及它的子类都是经典类
继承式用来创建新的类的一种方式,好处是减少重复代码
class People: def __init__(self,name,age): self.name=name self.age=age def walking(self): print(‘%s is walking ‘ %self.name) def talking(self): print(‘%s is talking ‘%self.name) class Teacher(People): pass class Student(People): pass t1=Teacher(‘egon‘,18) print(t1.name,t1.age) t1.walking() t1.talking() s1=Student(‘xiaobai‘,22) print(s1.name,s1.age) s1.talking() s1.walking() 执行结果 egon 18 egon is walking egon is talking xiaobai 22 xiaobai is talking xiaobai is walking
class People: def __init__(self,name,age,sex): self.name=name self.age=age self.sex=sex def walking(self): print(‘%s is walking ‘ %self.name) def talking(self): print(‘%s is talking ‘%self.name) class Teacher(People): def __init__(self,name,age,sex,level,salary): People.__init__(name,age,sex) self.level=level self.salary=salary def teaching(self): People.talking(self) print(‘%s is teaching‘%self.name) class Student(People): def __init__(self,name,age,sex,group): People.__init__(name,age,sex) self.group=group def studying(self): People.talking(self) print(‘%s is studying‘%self.name)
组合
class Date: def __init__(self,year,mon,day): self.year=year self.mon=mon self.day=day def tell_birth(self): print(‘出生于<%s>年 <%s>月 <%s>日‘%(self.year,self.mon,self.day)) class Teacher: def __init__(self,name,age,sex,year,month,day): self.name=name self.age=age self.sex=sex self.birth=Date(year,month,day) def teaching(self): print(‘%s is teaching‘%self.name) class Student: def __init__(self,name,age,sex,year,mon,day): self.name=name self.age=age self.sex=sex self.birth=Date(year,mon,day) def studying(self): print(‘%s is studying‘%self.name) xiaobai=Student(‘xiaobai‘,22,‘male‘,‘1995‘,‘3‘,‘16‘) xiaobai.birth.tell_birth() 执行结果 出生于<1995>年 <3>月 <16>日
继承和组合
class People: def __init__(self,name,age,sex,year,mon,day): self.name=name self.age=age self.sex=sex self.birth=Date(year,mon,day) def walking(self): print(‘%s is walking ‘ %self.name) def talking(self): print(‘%s is talking ‘%self.name) class Date: def __init__(self,year,mon,day): self.year=year self.mon=mon self.day=day def tell_birth(self): print(‘出生于<%s>年 <%s>月 <%s>日‘%(self.year,self.mon,self.day)) class Teacher(People): def __init__(self,name,age,sex,level,salary,year,mon,day): People.__init__(self,name,age,sex,year,mon,day) self.level=level self.salary=salary def teaching(self): People.talking(self) print(‘%s is teaching‘%self.name) class Student(People): def __init__(self,name,age,sex,year,mon,day,group): People.__init__(self,name,age,sex,year,mon,day) self.group=group def studying(self): People.talking(self) print(‘%s is studying‘%self.name)
父类要限制
1、子类必须有父类的方法
2、子类实现的方法必须跟父类的方法的名字一样
import abc class File(metaclass=abc.ABCMeta): @abc.abstractclassmethod def read(self): pass @abc.abstractclassmethod def write(self): pass
时间: 2024-10-31 14:22:02