码迷,mamicode.com
首页 > 编程语言 > 详细

python类的组合

时间:2018-12-09 12:18:49      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:int   提取   months   参数   mys   course   需要   choice   init   

类的组合,即在类实例化时,将另一个类的实例作为参数传入,这样可以将两个实例关联起来。

当类之间有显著不同,并且较小的类是较大的类所需要的组件时,用组合比较好。

例如,描述一个机器人类,这个大类是由很多互不相关的小类组成,如机械胳膊类、腿类、电池类等。

当类之间有很多相同的属性,提取这些统统的属性做成基类,用继承比较好。

class course:
    def __init__(self,name,price,period,teacher):
        self.name=name
        self.price=price
        self.period=period
        self.teacher=teacher
class teacher:
    def __init__(self,name,sex):
        self.name=name
        self.sex=sex
class student:
    def __init__(self,name,age,course):
        self.name=name
        self.age=age
        self.course=course
t1=teacher(‘Bob‘,38)
t2=teacher(‘Jack‘,45)
t3=teacher(‘Jane‘,45)
c1=course(‘python‘,6000,‘3 months‘,t2)#将teacher作为参数传递给课程实例
c2=course(‘linux‘,7000,‘5 months‘,t1)
c3=course(‘mysql‘,6500,‘5 months‘,t3)
d={‘1‘:c1,‘2‘:c2,‘3‘:c3}
name=‘Alice‘
age=21
while True:
    choice=input(‘please choice course:‘)
    if choice in d.keys():
        s1=student(name,age,d[choice])#将课程实例作为参数传递给学生实例
        print(s1.__dict__)
        print(‘%s choose course %s,%s is the teacher‘%(s1.name,s1.course.name,s1.course.teacher.name))
    elif int(choice)==0:
        exit(0)
    else:
        print(‘please input correct choice‘)

 

python类的组合

标签:int   提取   months   参数   mys   course   需要   choice   init   

原文地址:https://www.cnblogs.com/Forever77/p/10090242.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!