1、组合指的是,在一个类中以另外一个类的对象作为数据属性,称为类的组合。
2、作用是可以将两个本来不相关的类联系起来。一般是两个类之间有显著的不同,很多时候还要附属关系(有相同的属性也有不同的属性)。比如人和头,手机和电池等等
3、无纵向关系时用组合,有纵向关系时用继承
4、组合就是一个类中使用到另一个类,从而把几个类拼到一起。组合的功能也是为了减少重复代码。
class Turtle:
def __init__(self,x):
self.num = x
class Fish:
def __init__(self,x):
self.num = x
class Pool:
def __init__(self,x,y):
self.turtle = Turtle(x)
self.fish = Fish(y)
def number(self):
print("水池里总共%s只乌龟,共%s条鱼" % (self.turtle.num,self.fish.num))
#上面代码的输出结果为水池里总共1只乌龟,共10条鱼
class Date:
def __init__(self,year,mon,day):
self.year=year
self.mon=mon
self.day=day
def birth_info(self):
print("The birth is %s-%s-%s"%(self.year,self.mon,self.day))
class People:
def __init__(self,name,age,year,mon,day):
self.name=name
self.age=age
self.birth = Date(year,mon,day) #这就是组合
def walk(self):
print("%s is walking"%self.name)
class Teacher(People):
def __init__(self,name,age,year,mon,day,course):
People.__init__(self,name,age,year,mon,day)
self.course=course
def teach(self):
print("%s is teaching"%self.name)
class Student(People):
def __init__(self,name,age,year,mon,day,group):
People.__init__(self,name,age,year,mon,day)
self.group=group
def study(self):
print("%s is studying"%self.name)
t1=Teacher("alex",28,1989,9,2,"python")
s1=Student("jack",22,1995,2,8,"group2")
print(t1.name)
t1.walk()
t1.teach()
t1.birth.birth_info()
s1.birth.birth_info()
"""
alex
alex is walking
alex is teaching
The birth is 1989-9-2
The birth is 1995-2-8
"""
这个birth是子类Teacher从父类People继承过来的,而父类People的birth又是与Date这个类组合在一起的,所以,这个birth是一个对象。而在Date类下面有一个birth_info的技能,这样就可以通过调用Date下面的birth_info这个函数属性来知道老师t1的生日了。