继承:可以使用现有类的所有功能,并在无需重新编写原来的类的情况下对这些功能进行扩展
通过继承创建的新类称为“子类”或“派生类”
被继承的类称为“基类”、“父类”或“超类”
1、知识点
# Author: Mr.Xue
# 2019.10.29
# class People: # 经典类
class People(object): # 新式类
def __init__(self, name, age):
self.name = name
self.age = age
self.friends = []
def eat(self):
print("%s is eating..." % self.name)
def sleep(self):
print("%s is sleeping..." % self.name)
def talk(self):
print("%s is talking..." % self.name)
class Relation(object):
def make_friends(self, obj):
print("%s is making friends with %s" % (self.name, obj.name))
self.friends.append(obj)
class Man(People, Relation):
def __init__(self, name, age, money): # 对构造函数进行重构
#People.__init__(self, name, age) # 经典类的写法
super(Man, self).__init__(name, age) # 新式类的写法,和上面的语句效果相同
self.money = money
print("%s have $%s" % (self.name, self.money))
def swim(self):
print("%s is swiming..." % self.name)
def sleep(self): #重构父类的方法
People.sleep(self) # 先调用父类的方法
print("man is sleeping...")
class Woman(People, Relation):
def get_birth(self):
print("%s is born a baby...")
m = Man('Bob', 23, 10)
#m.swim()
#m.sleep()
w = Woman("John", 24)
m.make_friends(w)
w.name = "xue"
print(m.friends[0].name)
2、实例:学校、学生、老师
# Author: Mr.Xue
# 2091.10.27
#!_*_coding=utf-8_*_
class School(object):
def __init__(self, name, addr):
self.name = name
self.addr = addr
self.students = []
self.staffs = []
def enroll(self, stu_obj):
print("为学员%s办理注册手续" % stu_obj.name)
self.students.append(stu_obj)
def hire(self, staff_obj):
print("雇佣%s" % staff_obj.name)
self.staffs.append(staff_obj)
class SchoolMember(object):
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex
def tell(self):
pass
class Teacher(SchoolMember):
def __init__(self, name, age, sex, salary, course):
super(Teacher, self).__init__(name, age, sex)
self.salary = salary
self.course = course
def tell(self):
print("""
--- info of Teacher:
Name: %s
Age: %s
Sex: %s
Salary: %s
Course: %s
""" % (self.name, self.age, self.sex, self.salary, self.course))
def teach(self):
print("%s is teaching course[%s]" % (self.name, self.course))
class Student(SchoolMember):
def __init__(self, name, age, sex, stu_id, grade):
super(Student, self).__init__(name, age, sex)
self.stu_id = stu_id
self.grade = grade
def tell(self):
print("""
--- info of Student:
Name: %s
Age: %s
Sex: %s
Stu_id: %s
Grade: %s
""" % (self.name, self.age, self.sex, self.stu_id, self.grade))
def pay_tuition(self, tuition):
print("%s paid tuition $%s" % (self.name, tuition))
school1 = School('School1', 'ningbo')
t1 = Teacher('t1', 33, 'M', 5000, 'Python')
t2 = Teacher('t2', 34, 'F', 6000, 'C')
s1 = Student("s1", 18, 'F', 1001, 3)
s2 = Student("s2", 19, 'M', 1002, 4)
t1.tell()
s1.tell()
school1.hire(t1)
school1.enroll(s1)
school1.enroll(s2)
print(school1.staffs)
print(school1.students)
school1.staffs[0].teach()
for stu in school1.students:
stu.pay_tuition(4000)