Python full stack-combination

Combination: is to encapsulate an attribute of an object of a class, the encapsulated attribute is an object of another class.

Class: a class of things with the same attributes and skills

Object: is the concrete manifestation of the class, specific instance

class GameRole: #定义主角类
#name名字,ad攻击力,hp血量
	def __init__(self,name,ad,hp):
		self.name = name
		self.ad = ad
		self.hp = hp
	def armament_weapon(self,wea): #装备
		self.wea = wea
class Weapon: #武器类
    def __init__(self,name,ad):
        self.name = name
        self.ad = ad
    def fight(self,p1,p2):
        p2.hp = p2.hp - self.ad
        print("{}用{}打了{},{}掉了{}血,还剩{}血"
              .format(p1.name,self.name,p2.name,p2.name,self.ad,p2.hp))
#p1,p2,实例化GameRole的对象
p1 = GameRole('盖伦',20,500)
p2 = GameRole('亚索',50,200)
#三板斧,屠龙宝刀是武器类的对象
axe = Weapon('三板斧',60)
broadsword = Weapon('屠龙宝刀',10)
#p1调用装备这个方法,将三板斧装备给p1,作为p1的属性,注意,三板斧也是武器类的对象,这就叫组合
p1.armament_weapon(axe)
p1.wea.fight(p1,p2)	

Insert picture description here

As shown in the figure, p1 calls the equipment method, and passes the three-axe object in the weapon class as an attribute to the equipment method, and axe becomes the wea attribute, thus giving p1.
Published 26 original articles · praised 5 · visits 777

Guess you like

Origin blog.csdn.net/weixin_44730235/article/details/105165320