1、什么是继承
    继承是一种新建子类的方式,新建的类称之为子类/派生类,被继承的称之为父类/基类
 
    子类会遗传父类的属性
 
2、为何要用继承
    类是解决对象之间冗余问题的
    继承可以解决类与类之间的冗余问题
 
3、如何继承
    在python中支持多继承
 
    在python3中如果一个类没有继承任何父类,那么默认继承object类
 
    但凡是继承了object类的子类,以及该子类的子子孙孙类都能用到object内的功能,称之为新式类
    没有继承了object类的子类,以及该子类的子子孙孙类都能用不到object内的功能,称之为经典类
 
    ps:只有在python2中才区分经典类与新式类,python3中都是新式类
 
# class ParentClass1: #定义父类
#     pass
#
# class ParentClass2: #定义父类
#     pass
#
# class SubClass1(ParentClass1): #单继承,基类是ParentClass1,派生类是SubClass
#     pass
#
# class SubClass2(ParentClass1,ParentClass2): #python支持多继承,用逗号分隔开多个继承的类
#     pass
 
# print(SubClass2.__bases__)
# print(SubClass1.__bases__)
# print(ParentClass2.__bases__)

 

# 在子类派生的新方法中如何重用父类的功能,
# 方式一:指名道姓地访问父类的函数,与继承无关
# 方式二:super(),严格依赖继承
 
class People:
    school = "SH"
 
    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender
 
 
class Student(People):
    def __init__(self, name, age, gender, courses=None):
        People.__init__(self, name, age, gender,)
        if courses is None:
            courses = []
        self.courses = courses
 
    def choose_course(self, course):
        self.courses.append(course)
        print("学生%s 选课成功%s" % (self.name, self.courses))
 
 
class Teacher(People):
    def __init__(self, name, age, gender, level):
        People.__init__(self, name, age, gender,)
        self.level = level
 
    def score(self, stu_obj, num):
        stu_obj.num = num
        print('老师%s 为学生%s 打分%s' % (self.name, stu_obj.name, num))
 
 
stu1 = Student('tom',18,'male')
tea1 = Teacher('lili', 28, 'female', 10)
 
print(stu1.__dict__)
print(tea1.__dict__)
# print(stu1.school)

  

 

posted on 2021-04-13 19:56  lzl_121  阅读(39)  评论(0编辑  收藏  举报