1. 组合:一个对象的属性值是另一个类的实例对象,alex.weapon是Weapon类的对象
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Dog: def __init__(self,name,aggr,hp,kind): self.name=name self.aggr=aggr self.hp=hp self.kind=kind def bite(self,person): person.hp-=self.aggr class Person: def __init__(self,name,aggr,hp,sex): self.name=name self.aggr=aggr self.hp=hp self.sex=sex self.money=0 def attack(self,dog): dog.hp-=self.aggr def get_weapon(self,weapon): if self.money >= weapon.price: self.money -=weapon.price self.weapon=weapon self.aggr +=weapon.aggr else: print('余额不足,请先充值!') class Weapon: def __init__(self,name,aggr,njd,price): self.name=name self.aggr=aggr self.njd=njd self.price=price def hand18(self,stroke): #武器放大招 if self.njd>0: stroke.hp -= self.aggr*2 self.njd -=1 alex=Person('alex',0.5,100,'不详') jin=Dog('金老师',100,500,'teddy') w=Weapon('打狗棒',100,3,998) alex.money += 1000 #充值1000 #alex获取装备 alex.get_weapon(w) print('alex获取的装备对象:',alex.weapon) print('alex获取装备后总的血量:',alex.aggr) print(alex.__dict__) print('---------------------') alex.attack(jin) #alex打狗,狗的血掉了 print('alex打狗后,狗的血量:',jin.hp) print('++++++++++++++++++++++') alex.weapon.hand18(jin) #alex用获取到的装备的大招打攻击狗 print('alex用大招攻击狗后,狗的血量:',jin.hp)
2. 利用类的组合,求一个圆环的面积和周长
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from math import pi class Circle: def __init__(self,r): self.r=r def area(self): #面积 return pi*(self.r**2) def perimeter(self): #周长 return 2*pi*self.r class Ring: def __init__(self,outside_r,inside_r): self.outside_c=Circle(outside_r) self.inside_c=Circle(inside_r) def area(self): return self.outside_c.area()-self.inside_c.area() def perimeter(self): return self.outside_c.perimeter()+self.inside_c.perimeter() #求一个圆环的面积和周长 ring=Ring(20,10) print(ring.area()) print(ring.perimeter())
3. 利用类的组合,创建一个老师类, 老师有生日,生日也可以是一个类(年月日)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Birthday(): def __init__(self,year,month,day): self.year=year self.month=month self.day=day class Course: language = ['Chinese'] def __init__(self,course_name,period,price): self.name = course_name self.period = period self.price = price def func(self): pass class Teacher(): def __init__(self,name,age,sex,birthday): self.name=name self.age=age self.sex=sex self.birthday=birthday self.course=Course('python','6 months',2000) #实例对象属性是类Course实例对象 b=Birthday('2020','02','27') t1=Teacher('小王',28,'女',b) #实例对象t1的属性birthday是类Birthday实例对象 print('老师生日的年份:',t1.birthday.year) print('老师生日的月份:',t1.birthday.month) print('----------------------') print('老师教的课程名称:',t1.course.name) print('老师教的课程价格:',t1.course.price)
4. 当类之间有显著不同,并且较小的类是较大的类所需要的组件时,用组合比较好;
5. 学校管理系统