定义:定义一个人的类包含头,躯干,手,脚等数据属性,这些属性可以通过一个类实例化的对象
用途:1.做关联
2.小的组合为大的
例1.
# -*- coding: utf-8 -*- class School: def __init__(self,name,addr): self.name=name self.addr=addr def enrool(self): print('%s正在招生'% self.name) class Course: def __init__(self,name,price,period,school): self.name=name self.price=price self.period=period self.school=school s1=School('oldboy','北京') s2=School('oldboy','南京') s3=School('oldboy','西安') c1=Course('Linux',1000,'1day',s1) print(c1.school.name)
例2.选课
# -*- coding: utf-8 -*- class School: def __init__(self,name,addr): self.name=name self.addr=addr def enrool(self): print('%s正在招生'% self.name) class Course: def __init__(self,name,price,period,school): self.name=name self.price=price self.period=period self.school=school s1=School('oldboy','北京') s2=School('oldboy','南京') s3=School('oldboy','西安') msg={ ''' 1 oldboy 北京校区 2 oldboy 南京校区 3 oldboy 西安校区 ''' } while True: print(msg) menu={ '1':s1, '2': s2, '3': s3 } choice=input('请选择学校》》') school_obj=menu[choice] name=input('课程名》》') price=input('价格》》') period=input('学习时长') new_course=Course(name,price,period,school_obj) print('课程 %s 属于学校 %s'%(new_course.name,new_course.school.name))