继承方式的区别:
(新式类用的多)
新式类:
class SonClass(object): super(SonClass,self).__init__(self,name,age,...)
经典类:
class Son: ParentClass.__init__(self,name,age,...)
类的继承:从父类(基类)中继承,可复用已有代码
继承特点:
总是从某个类继承,没有合适父类时从object类继承;
代码饭粒1:
#!/usr/bin/env python # -*- coding: utf-8 -*- class A(object): def __init__(self,name,age): self.name = name self.age = age self.sex = 'woman' def aa(self): print('in the aa...') class B(A): def __init__(self,name,age,sex): A.__init__(self,name,age) print(self.name,self.age,self.sex) def aa(self): print("in the ba...") def bb(self): print('in the bb...') b = B('rose','22','girl') b.aa() # 输出: rose 22 woman in the ba...
多继承
#!/usr/bin/env python # -*- coding: utf-8 -*- class SchoolMenber(object): '''学校成员基类''' number = 0 def __init__(self,name,age): self.name = name self.age = age self.enroll() def enroll(self): print("%s is enrolling..." % self.name) SchoolMenber.number += 1 def tell(self): print('-------%s info-----' % self.name) for k,v in self.__dict__.items(): print('\t',k,v) print('--------end--------') def __del__(self): print("%s is dismissed." % self.name) SchoolMenber.number -= 1 class School(object): def address(self,addr): print("You are teaching in %s." % addr) class Teacher(SchoolMenber,School): def __init__(self,name,age,salary,course): super(Teacher,self).__init__(name,age) self.salary = salary self.course = course def teaching(self): print("%s is teaching %s" % (self.name,self.course)) class Student(SchoolMenber): def __init__(self,name,age,course,fee): SchoolMenber.__init__(self,name,age) self.course = course self.fee = fee def pay_fee(self,amount): print("%s has just paied %s" % (self.name,amount)) self.amount += amount t1 = Teacher('Alex',29,9999,'python') s1 = Student('fone',23,'python',6500) s2 = Student('lqw',21,'python',6000) print(SchoolMenber.number) t1.tell() s1.tell() del s2 print(SchoolMenber.number) t1.address('GD')
多继承时的继承顺序
示例代码:
#!/usr/bin/env python # -*- coding: utf-8 -*- class A(object): def __init__(self): print('A...') class B(A): def __init__(self): print('B...') class C(A): def __init__(self): print('C...') class D(B,C): def __init__(self): print('D...') D()
继承关系及继承顺序:广度查询

在python3中,无论是新式类还是经典类,都是广度查询。
在python2中为深度查询,即先在左边查询到底,不存在再到邮编查询,上栗顺序为D>B>A>C (了解即可)
实例间的相互调用:
#!/usr/bin/env python # -*- coding: utf-8 -*- class F1: def __init__(self,n): self.N = n print("F1") class F2: def __init__(self,arg1): self.a = arg1 print("F2") class F3: def __init__(self,arg2): self.b = arg2 print("F3") o1 = F1('alex') o2 = F2(o1) o3 = F3(o2) print(o3.b.a.N)
# 输出:
F1
F2
F3
alex
posted on
浙公网安备 33010602011771号