繼承:可以使用現有類的所有功能,並在無需重新編寫原來的類的情況下對這些功能進行擴展
通過繼承創建的新類稱爲“子類”或“派生類”
被繼承的類稱爲“基類”、“父類”或“超類”
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)