可以将那些重复的,固定的东西提出来,单独定义一个类。
例如:
1 class Course: 2 def __init__(self,course_name,course_period,course_price): 3 self.course_name=course_name 4 self.course_period=course_period 5 self.course_price=course_price 6 def tell_info(self): 7 print(‘<课程名:%s 周期:%s 价格:%s>‘ %(self.course_name,self.course_period,self.course_price)) 8 9 python=Course(‘Python‘,‘6mons‘,3000) 10 linux=Course(‘Lnux‘,‘3mons‘,2000) 11 bigdata=Course(‘BigData‘,‘1mons‘,1000)
例如这种:
1 class OldboyPeople: 2 school = ‘oldboy‘ 3 def __init__(self,name,age,sex): 4 self.name=name 5 self.age=age 6 self.sex=sex 7 8 def eat(self): 9 print(‘is eating‘) 10 11 class OldboyStudent(OldboyPeople): 12 13 def __init__(self,name,age,sex): 14 OldboyPeople.__init__(self,name,age,sex) 15 self.course=[] 16 17 def learn(self): 18 print(‘%s is learning‘ %self.name) 19 20 21 class OldboyTeacher(OldboyPeople): 22 def __init__(self,name,age,sex,salary,title): 23 OldboyPeople.__init__(self,name,age,sex) 24 self.salary=salary 25 self.title=title 26 self.course=[] 27 28 def teach(self): 29 print(‘%s is teaching‘ %self.name) 30 31 32 class Course: 33 def __init__(self,course_name,course_period,course_price): 34 self.course_name=course_name 35 self.course_period=course_period 36 self.course_price=course_price 37 def tell_info(self): 38 print(‘<课程名:%s 周期:%s 价格:%s>‘ %(self.course_name,self.course_period,self.course_price)) 39 40 python=Course(‘Python‘,‘6mons‘,3000) 41 linux=Course(‘Lnux‘,‘3mons‘,2000) 42 bigdata=Course(‘BigData‘,‘1mons‘,1000) 43 44 # python.tell_info() 45 46 47 egon_obj=OldboyTeacher(‘egon‘,18,‘male‘,3.1,‘沙河霸道金牌讲师‘) 48 # 49 # egon_obj.course.append(python) 50 # egon_obj.course.append(linux) 51 # 52 # for obj in egon_obj.course: 53 # obj.tell_info() 54 55 56 yl_obj=OldboyStudent(‘yanglei‘,28,‘female‘) 57 yl_obj.course.append(python) 58 59 for i in yl_obj.course: 60 # print(i.course_name,i.course_period,i.course_price) 61 i.tell_info()
时间: 2024-10-17 17:47:17