组合
软件重用的重要方式除了继承之外还有另外一种方式,即:组合
组合指的是,在一个类中以另外一个类的对象作为数据属性,称为类的组合
class People: def __init__(self,name,age,sex): self.name = name self.age = age self.sex = sex class Renwen(People): def __init__(self,name,age,sex,weapon): super().__init__(name,age,sex) self.weapon = weapon self.attribute = [] #锐雯的属性列表 def skill(self): print(‘%s is skill‘%self.name) class Teacher(People): def __init__(self,name,age,sex,level): super().__init__(name,age,sex) self.level = level def teach(self): print("%s is teaching" %self.name) class Attribute: def __init__(self,damage,spell,armor): self.danage = damage self.spell = spell self.armor =armor def tell_info(self): print("生命值:%s,法术:%s,护甲:%s"%(self.danage,self.spell,self.armor)) rewen = Renwen(‘锐雯‘,22,‘female‘,"砍刀") teacher1 =Teacher(‘林书行‘,30,‘male‘,20) a = Attribute(200,20,100)#创建属性对象 rewen.attribute.append(a) #添加属性值 #打印出属性值 for i in rewen.attribute: i.tell_info()
原文地址:https://www.cnblogs.com/Mryang123/p/8597973.html
时间: 2024-10-31 20:06:05