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

Python类的组合

时间:2018-05-09 19:25:23      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:man   游戏   相关   code   ==   class   数据   elf   enter   

组合指的是,在一个类中以另外一个类的对象作为数据属性,称为类的组合。作用是可以将两个本来不相关的类联系起来。

class Monster(object):
    def __init__(self,hp):
        self.hp=hp
class Wepon():
    damage=10
class Superman(object):
    def __init__(self,hp):
        self.__hp=hp
        self.damage=Wepon()  #这就是组合
    def gongji(self,monster):
        monster.hp-=self.damage.damage


if __name__==‘__main__‘:
    print((‘游戏开始‘).center(30,‘*‘))
    print(‘怪兽产生了‘)
    monster1=Monster(100)
    print(‘怪兽的血量是%d‘%monster1.hp)
    s1=Superman(100)
    print(‘产生了一个超人,攻击力是%d‘%s1.damage.damage)
    s1.gongji(monster1)
    print(‘怪兽受到攻击,血量变成%d‘%monster1.hp)

 

Python类的组合

标签:man   游戏   相关   code   ==   class   数据   elf   enter   

原文地址:https://www.cnblogs.com/linshuhui/p/9015843.html

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