Python 类的构造,继承,多重继承
#类的默认构造与结构 class people: __id = 1 #私有成员,无法在类外访问,在变量前面加两个下划线__表示私有变量 在类外访问非法 m_age = 2 #公有成员,可以在类外访问 m_name ='' def __init__(self,id,age,name): #__init__为类的默认构造函数,在类初始化时候,自动执行该参数 self.__id = id #self相当于C++中的this指针,相当于指向该类的指针使用"self."代表类成员 self.m_age = age self.m_name =name def Get__id(self): #获取私有成员 return self.__id def speak(self): print("%s说: 我的id为 %d,今年 %d 岁" % (self.m_name,self.__id, self.m_age)) p = people(id =1,age =18,name ='小刚') #实例化类, p.speak() #类的继承 class DoSomething(people): m_dosomething ='' def __init__(self,id,age,name,dosomething): people.__init__(self,id,age,name) #调用父类的构造函数 self.m_dosomething =dosomething #子类变量赋值 def speak(self): #重写父类的函数 print("%s说: 我的id为 %d,今年 %d 岁,我会%s" % (self.m_name, self.Get__id(), self.m_age,self.m_dosomething)) temp = DoSomething(id =1,age = 18,name ='小刚',dosomething= '画画') temp.speak() super(DoSomething,temp).speak() #super函数,用与使用子类调用父类被重写的函数 class aa: def __init__(self): self.a =1 #变量可以直接在构造中定义,并在类外使用 self.b =2 ppp= aa() print(ppp.a, ppp.b) # people被Dosomething 继承 Dosomething被lovesomething继承,因为people被Dosomething继承了,所以people也会自动继承于lovesomething class lovesomething(DoSomething): m_love ='' def __init__(self,id,name,age,dosomething,love): # people.__init__(self,id,age,name) #这里踩坑,只需要包含Dosomething的构造即可 DoSomething.__init__(self,id,age,name,dosomething) self.m_love =love def speak(self): print("%s说: 我的id为 %d,今年 %d 岁,我会%s,我喜欢%s。" % (self.m_name, self.Get__id(), self.m_age, self.m_dosomething,self.m_love)) temp2= lovesomething(id =1,age = 18,name ='小刚',dosomething= '画画',love= '打篮球') temp2.speak() #多重继承 class A: def __init__(self, high): self.m_high =high def speak(self): print(' 高:%d',self.high) class B: def __init__(self,width): self.m_width=width def speak(self): print(' 宽:%d ',self.width) class C(A,B): #继承A和B def __init__(self,width,high): A.__init__(self,high) B.__init__(self,width) def speak(self): #重写A和B类的函数 print('求乘积 %d x %d = %d' %(self.m_width,self.m_high,self.m_width * self.m_high)) temp3= C(2,3) temp3.speak()