import abc class AllFile(metaclass=abc.ABCMeta): @abc.abstractmethod def read(self): pass # 父类定义抽象的方法,子类必须实现 @abc.abstractmethod def write(self): pass class Txt(AllFile): def read(self): print("txt read") def write(self): print("txt write") class Mem(AllFile): def read(self): print("mem read") def write(self): print("mem write") m = Mem() m.read() m.write()
继承顺序:
Java ,C#只能继承一个类,Python可以继承多个类
class A: def test(self): print("this is A") class B(A): # def test(self): # print("this is B") pass class D(B): # def test(self): # print("this is D") pass class C(A): # def test(self): # print("this is C") pass class E(C): # def test(self): # print("this is E") pass class F(D,E): # def test(self): # print("this is F") pass print(F.__mro__) ‘‘‘ F.__mro__ 揭秘了F的继承顺序 (<class ‘__main__.F‘>, <class ‘__main__.D‘>, <class ‘__main__.B‘>, <class ‘__main__.E‘>, <class ‘__main__.C‘>, <class ‘__main__.A‘>, <class ‘object‘>) ‘‘‘ f = F() f.test() # F-->D-->B-->E-->C-->A
Python会计算一个方法解析顺序(MRO) 列表,这个列表就是一个简单的所有基类的线性顺序表
注意:Python2 与Python3 中的继承顺序是不一样的
子类中调用父类的方法
class Vehicle: Country = "China" def __init__(self,name,speed,load,power): self.Name = name self.Speed = speed self.Load = load self.Power = power def run(self): print("running...") class Subway(Vehicle): def __init__(self,name,speed,load,power,line): Vehicle.__init__(self,name,speed,load,power) self.Line = line def show_info(self): print("%s %d号线" %(self.Name,self.Line)) def run(self): Vehicle.run(self) print("%s %d号线,以%s的速度在运行" %(self.Name,self.Line,self.Speed)) line3 = Subway("深圳地铁","100km/s",10000,"电",3) line3.show_info() line3.run() ‘‘‘ 深圳地铁 3号线 running... 深圳地铁 3号线,以100km/s的速度在运行 ‘‘‘
super调用父类的方法
class Vehicle: Country = "China" def __init__(self,name,speed,load,power): self.Name = name self.Speed = speed self.Load = load self.Power = power def run(self): print("running...") class Subway(Vehicle): def __init__(self,name,speed,load,power,line): # Vehicle.__init__(self,name,speed,load,power) super().__init__(name,speed,load,power) self.Line = line def show_info(self): print("%s %d号线" %(self.Name,self.Line)) def run(self): # Vehicle.run(self) super().run() print("%s %d号线,以%s的速度在运行" %(self.Name,self.Line,self.Speed)) line3 = Subway("深圳地铁","100km/s",10000,"电",3) line3.show_info() line3.run() ‘‘‘ 深圳地铁 3号线 running... 深圳地铁 3号线,以100km/s的速度在运行 ‘‘‘
原文地址:https://www.cnblogs.com/xiangtingshen/p/10459741.html
时间: 2024-10-17 08:02:09