python 定义类 学习2

 

 构造函数的变量 也叫做 实例变量

class role(): # 传参数

    def __init__(self,name,role,weapon,life_value=100,moneny=15000):
        # 构造函数
        # 实例化过程中做一些类的初始化工作
        self.name = name
        self.role = role
        self.weapon = weapon
        self.life_value = life_value
        self.moneny = moneny

    def shot(self):  # 类的方法,功能(动态属性)
        print("shotting")

    def got_shot(self):
        print("on,%s got shoot..." % self.name)

    def buy_gun(self,gun_name):
        print("%s just bought %s" %(self.name,gun_name))

b1 = role('mike','police','AK47')


b1.got_shot() # 调用
# on,mike got shoot...
b1.buy_gun("B21")  # mike just bought B21


b2 = role('ben','terrorist','AK47')
b2.got_shot() # role.got_shot(b2)
# on,ben got shoot...


b2.buy_gun("B21")   # ben just bought B21
b2.buy_gun("B46")   # ben just bought B46
print(b2.weapon)    # AK47

打印b2.weapon 还是AK47 部署B21 B46

 

class role(): # 传参数

    def __init__(self,name,role,weapon,life_value=100,moneny=15000):
        # 构造函数
        # 实例化过程中做一些类的初始化工作
        self.name = name
        self.role = role
        self.weapon = weapon
        self.life_value = life_value
        self.moneny = moneny

    def shot(self):  # 类的方法,功能(动态属性)
        print("shotting")

    def got_shot(self):
        print("on,%s got shoot..." % self.name)

    def buy_gun(self,gun_name):
        print("%s just bought %s" %(self.name,gun_name))
        self.weapon = gun_name

b1 = role('mike','police','AK47')


b1.got_shot() # 调用
# on,mike got shoot...
b1.buy_gun("B21")  # mike just bought B21


b2 = role('ben','terrorist','AK47')
b2.got_shot() # role.got_shot(b2)
# on,ben got shoot...


b2.buy_gun("B21")   # ben just bought B21
b2.buy_gun("B46")   # ben just bought B46
print(b2.weapon)    # B46  改了

 

posted @ 2018-05-11 11:16  minger_lcm  阅读(181)  评论(0)    收藏  举报