本文共 1216 字,大约阅读时间需要 4 分钟。
# -*-coding:utf-8 -*-__author__ = 'xiaojiaxin'__file_name__ = '继承'# 继承# 类继承类# class father:基类,父类# class son :派生类,子类## class grandfather:# def 下棋(self):# pass## class father(grandfather):## def 篮球(self):# pass# def 足球(self):# pass# def 喝酒(self):# pass# def 电影(self):# pass# class son(father): #(father)表示这个孩子的父亲就是father# def 篮球(self):# pass# def 下棋(self):# pass#
class F: def f1(self): print("F.f1") def f2(self): print("F.f2")class S(F): def s1(self): print("S.s1") def f2(self): #不再继承父类的f2方法 print("S.f2")"""obj=S()obj.s1()obj.f1()obj.f2()"""'''obj1=S()obj1.s1() #s1中的self是形参,此时代指obj1obj.f1() #f1中的self是形参,self永远指向f1()方法的调用者'''
class F1: def f1(self): print("F.f1") def f2(self): print("F.f2")class S1(F): def s1(self): print("S.s1") def f2(self): #下面可以继续继承父类方法 #super(S1,self).f2() #找到父类,执行父类或者基类中的方法 F1.f2(self) #与上句话等价 print("S.f2")obj2=S1()obj2.f2() #super(S1,self).f2()# F.f2# S.f2# F.f2 #F1.f2(self)# S.f2
总结:调用父类的方法有两种方式:
super(S1,self) 推荐F1.f2(self)转载于:https://blog.51cto.com/10777193/2096440