Python —— 面向对象
Python —— 面向对象
继承与多继承
1 class classmate: # 父类、超类 2 def __init__(self,name,sex,age): 3 self.name = name 4 self.sex = sex 5 self.age = age 6 def eat(self,foodname): 7 print("%s要吃%s" % (self.name,foodname)) 8 def drink(self,drinkname): 9 print("%s要喝%s" % (self.name,drinkname)) 10 11 class Programmer(classmate): # 子类。语法:子类名(要继承的类的名) 12 def __init__(self,name,sex,age,job = '程序员'): 13 super().__init__(name,sex,age) 14 self.job = job 15 def work(self): 16 print("%s的工作是%s" % (self.name,self.job)) 17 18 class Teacher(classmate): 19 def __init__(self,name,sex,age,job = '老师'): 20 super().__init__(name,sex,age) # super方法调用父类中的双下init方法(因子类和父类有同样的双下init方法,子类的对象只会调用子类中的双下init方法) 21 self.job = job 22 def work(self): 23 print("%s的工作是%s" % (self.name,self.job)) 24 25 tea1 = Teacher("Jing","女",25) # 定义一个老师对象 26 tea1.work() # 结果:Jing的工作是老师 27 tea1.drink("水") # 结果:Jing要喝水 28 print(tea1.name) # Jing 29 pro1 = Programmer("Amy","女",26) 30 pro1.work() 31 print(pro1.name)
二、多继承
同学中有男同学做了老师,也有女同学做了老师,有男同学做了程序员,也有女同学做了程序员。
即有人同时要继承老师类,也要继承 男生类 / 女生类,有人要继承程序员类,也要继承 男生类 / 女生类。
1 class Classmate: 2 def __init__(self,name,sex,age): 3 self.name = name 4 self.sex = sex 5 self.age = age 6 def eat(self,foodname): 7 print("%s要吃%s" % (self.name,foodname)) 8 def drink(self,drinkname): 9 print("%s要喝%s" % (self.name,drinkname)) 10 11 class Programmer(Classmate): 12 def __init__(self,name,sex,age,job = '程序员'): 13 super().__init__(name,sex,age) 14 self.job = job 15 def work(self): 16 print("%s的工作是%s" % (self.name,self.job)) 17 class Male(Classmate): 18 def drink(self): 19 print("%s要喝的是酒。"%self.name) 20 class Female(Classmate): 21 def drink(self): 22 print("%s要喝的是果汁。"%self.name) 23 class Male_programmer(Programmer,Male): 24 pass 25 class Female_programmer(Programmer,Female): 26 pass 27 28 pro1 = Female_programmer("Amy","女",26) 29 pro1.drink() # 结果:Amy要喝的是果汁。 30 pro2 = Male_programmer("Bob","男",27) 31 pro2.drink() # 结果:Bob要喝的是酒。