```通过继承创建的新类称为“子类”或“派生类”。
被继承的类称为“基类”、“父类”或“超类”。
继承概念的实现方式主要有2类:实现继承、接口继承。
1、实现继承是指使用基类的属性和方法而无需额外编码的能力;
2、接口继承是指仅使用属性和方法的名称、但是子类必须提供实现的能力(子类重构爹类方法);
## 最简单的继承
class person(object):
def talk(self):
print('talk english....')
class ypeople(person):
# def talk(self): #要是没有重新定义talk会调用父类里的talk
print("talk chinese")
def walk(self):
print("yperson is runing....")
b=ypeople()
b.talk()
b.walk()
## 先继承再重构
class person(object): 父类
def __init__(self,name,age):
self.name=name
self.age=age
self.sex="normal"
def talk(self):
print('talk english....')
class bperson(object):
pass
class ypeople(person):
def __init__(self,name,age,strength): #先继承,再重构
person.__init__(self,name,age)
self.www="www"
print(self.name,self.age,self.sex)
def talk(self): #要是没有重新定义talk会调用父类里的talk
person.talk(self) #继承方法(一般不这么做,重复执行)
print("talk chinese")
def walk(self):
print("yperson is working...")
b=ypeople("王东",30,"strong")
b.talk()
b.walk()
## 类的继承运用例子
class School(object):
""""学校成员基类"""
number=0
def __init__(self,name,age,sex):
self.name=name
self.age=age
self.sex=sex
self.enroll() #在基类里内部调用(相当于子类默认调用)
def enroll(self):
"""注册"""
print("%s欢迎加入我们学院!"%self.name)
School.number+=1 #把值赋给公有属性(变成全局的)直接self.number只是在实例里面创建了一个变量number=0然后加1
def tell(self):
"""打印自己的信息"""
print("------info:%s-------"%self.name)
for k,v in self.__dict__.items():
print("\t",k,v)
print("------end-------" )
def __del__(self): # 析构
print("[%s] 被开除了!"%self.name)
School.number-=1
class newschool(object):
def openschool(self,addr):
print("open in the %s"%addr)
class Teacher(School,newschool): # 多继承(继承多个类)
"""讲师类"""
def __init__(self,name,age,sex,salary,course):
#School.__init__(self,name,age,sex) #经典类
super(Teacher,self).__init__(name,age,sex) # 新式类
self.salary=salary
self.coures=course
def teaching(self):
print("Teacher [%s] is teaching [%s]"%(self.name,self.coures))
class Student(School):
"""学生类"""
def __init__(self,name,age,sex,course,fee):
School.__init__(self,name,sex,age)
self.course=course
self.fee=fee
self.amount=0
def pay_fee(self,amount):
print("student [%s] has just paid [%s]"%(self.name,self.amount))
self.amount+=amount
t1=Teacher("王肖",29,'F*M',20000,"Python")
s1=Student("王鼎",26,"N/A",'Python',30000)
s2=Student("苏晓",22,"F","Python",5000)
print(School.number) #输出总共创建次数
print(t1.number) #输出t1实例本身创建次数
print(School.number) #输出总共创建次数
del s1 #删除s1
print(School.number) #输出总共创建次数
a=s1.__dict__ #把信息转换成列表
print(a)
t1.tell()
t1.openschool("上海") #多继承测试
网页名称:类的继承和类继承运用
网页链接:
http://njwzjz.com/article/iejjig.html