标签:实验 子类 color self ranch sha 带来 成员 pytho
在python还支持多继承,但是一般我们很少用,有些语言干脆就不支持多继承,有多继承,就会带来两个概念,经典类和新式类。
之前我们都是讲的单继承,那么什么是多继承呢?说白了,就是:子类可以继承多个父类,就叫多继承。
class SchoolMember(object): #SchoolMember类 ‘‘‘学校成员基类‘‘‘ def tell(self): print("the schoolmeber is tell...") class School(object): #School类 """学校类""" def open_branch(self,addr): print("openning a new branch in",addr) class Teacher(SchoolMember,School): #子类Teacher同时继承了SchoolMember,School两个类 "讲师类" def teaching(self): "讲课方法" print("Teacher xiaogao is teaching python") t1 = Teacher() t1.tell() #拥有父类SchoolMember的tell方法 t1.open_branch("shanghai") #拥有父类School的open_branch方法
1、概念
新式类定义时必须继承object类,被定义继承了object类的,就叫做新式类
class Person(object): #继承object类 "新式类"
2、继承构造方法
新式类初始化构造方法用super关键字去继承
super(子类,self).__init__(name,age)
3、调用父类中相同方法或者相同属性的顺序
新式类多继承的调用方法是顺序是:广度优先查询,如下图:
代码实验如下:
①全部代码
class A(object): #新式类 def __init__(self): self.n = "A" class B(A): def __init__(self): self.n = "B" class C(A): def __init__(self): self.n = "C" class D(B,C): def __init__(self): self.n = "D" d = D() print(d.n) #输出 D 全部代码
先找自己本身类的属性,输出D
②注释D类中代码
class A: def __init__(self): self.n = "A" class B(A): def __init__(self): self.n = "B" class C(A): def __init__(self): self.n = "C" class D(B,C): pass d = D() print(d.n) #输出 B
③注释B类中的代码
class A: def __init__(self): self.n = "A" class B(A): pass class C(A): def __init__(self): self.n = "C" class D(B,C): pass d = D() print(d.n) #输出 A
④注释C类中的代码
class A(object): def __init__(self): self.n = "A" class B(A): pass class C(A): pass class D(B,C): pass d = D() print(d.n) #输出 A
1、概念
经典类定义,什么都不继承
class Person: "经典类"
2、继承构造方法
父类.__init(self,name,age)
3、调用父类中相同方法或者相同属性的顺序
经典类多继承的调用方法是顺序是:深度优先查询,如下图:
代码实验如下:
①全部代码
class A:#经典类 def __init__(self): self.n = "A" class B(A): pass def __init__(self): self.n = "B" class C(A): def __init__(self): self.n = "C" class D(B,C): def __init__(self): self.n = "D" d = D() print(d.n) #输出 D
②注释D类中代码
class A: def __init__(self): self.n = "A" class B(A): def __init__(self): self.n = "B" class C(A): def __init__(self): self.n = "C" class D(B,C): pass d = D() print(d.n) #输出 B
③注释B类中的代码
class A: def __init__(self): self.n = "A" class B(A): pass class C(A): def __init__(self): self.n = "C" class D(B,C): pass d = D() print(d.n) #输出 A
④注释A类中的代码
class A: pass class B(A): pass class C(A): def __init__(self): self.n = "C" class D(B,C): pass d = D() print(d.n) #输出 C
总结:
标签:实验 子类 color self ranch sha 带来 成员 pytho
原文地址:http://www.cnblogs.com/Keep-Ambition/p/7290656.html