一、永不变的三个问答
1、什么是继承
继承一种新建类的方式,新建的类称之为子类 / 派生类,被继承的类称之为父类 \ 基类 \ 超类
2、为什么要用继承
减少类与类之间代码元素
3、如何用继承
class Parent1: # 继承的父类
pass
# print(Parent1.__bases__)
class Parent2: #子类
pass
# print(Parent2.__bases__)# 子类
class Sub1(Parent1): # 没加()时,无法继承父类
pass
class Sub2(Parent1, Parent2): # 可以‘,,,’ 一直写下去
pass
# 如何查看继承关系
print(Sub1.__bases__)
print(Sub2.__bases__)
二、python中继承的特点:
1. 子类可以遗传/重用父类的属性
2. python中一个子类可以同时继承多个父类
3. 在继承背景下去说,python中的类分为两种:新式类,经典类
新式类:
但凡继承了object的类Foo,以及该类的子类...都是新式类,在python3中一个类即便是没有显式地继承任何类,默认就会继承object,
即python3中所有的类都是新式类
经典类:
没有继承object的类,以及该类的子类...都是经典类在python2中才区分新式类与经典类,在python2中一个类如果没有显式地继承任何类,
也不会继承object
三、在单继承背景下的属性查找优先级: 对象->对象的类->父类->父类.....
class Foo:
# xxx=444
pass
class Bar1(Foo):
# xxx=333
pass
class Bar2(Bar1):
# xxx=222
pass
obj=Bar2()
# obj.xxx=111
print(obj.xxx)
四、如何在子类派生的新方法中重用父类功能
源代码:
class OldboyStudent():
school = 'Oldboy'
def __init__(self, name, age, sex, score=0):
school = 'oldboy'
self.name = name
self.age = age
self.sex = sex
self.score = score
class OldboyTeacher():
school = 'Oldboy'
def __init__(self, name, age, sex, level=10):
school = 'Oldboy'
self.name = name
self.age = age
self.sex = sex
self.level = level
def score(self, stu, num):
stu.score = num
stu1 = OldboyStudent('bp', 1000, 'shemale')
print(stu1.__dict__)
tea1 = OldboyTeacher('dg', 20, 'sunmale')
print(tea1.__dict__)
在子类派生出的新方法中重用父类功能的方式一:
指名道姓地引用某一个类中的函数
总结:
1. 与继承无关
2. 访问是类的函数,没有自动传值的效果
class OldboyPeople:
school = 'Oldboy'
def __init__(self, name, age, sex):
self.name = name
self.age = age
self.sex = sex
class OldboyStudent(OldboyPeople):
def __init__(self, name, age, sex, score=0):
OldboyPeople.__init__(self,name, age, sex)
self.score = score
def choose_course(self):
print('%s choosing course' % self.name)
class OldboyTeacher(OldboyPeople):
def __init__(self, name, age, sex, level):
OldboyPeople.__init__(self,name, age, sex)
self.level = level
def score(self, stu, num):
stu.score = num
stu1 = OldboyStudent('bp', 1000, 'shemale', score=0)
print(stu1.__dict__)
tea1 = OldboyTeacher('dg', 20, 'sunmale', level=10)
print(tea1.__dict__)
在子类派生出的新方法中重用父类功能的方式二:super()必须在类中用
在python2中:super(自己的类名,自己的对象)
在python3中:super()
调用该函数会得到一个特殊的对象,该对象专门用来访问父类中的属性,!!!完全参照mro列表!!!!
总结:
1. 严格依赖继承的mro列表
2. 访问是绑定方法,有自动传值的效果
class OldboyPeople:
school='Oldboy'
def __init__(self,name,age,sex):
self.name=name
self.age=age
self.sex=sex
class OldboyStudent(OldboyPeople):
def __init__(self,name,age,sex,score=0):
super(OldboyStudent,self).__init__(name,age,sex)
self.score=score
def choose_course(self):
print('%s choosing course'%self.name)
class OldboyTeacher(OldboyPeople):
def __init__(self,name,age,sex,level):
super().__init__(name,age,sex)
self.level=level
def score(self,stu,num):
stu.score=num
stu1=OldboyStudent('bp',1000,'shemale',0)
print(stu1.__dict__)
tea1=OldboyTeacher('dg',20,'male',10)
print(tea1.__dict__)