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

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  改了

 

相关文章:

  • 2022-02-06
  • 2021-11-02
  • 2021-10-25
  • 2021-07-25
  • 2022-12-23
  • 2021-09-23
  • 2021-06-03
  • 2021-11-13
猜你喜欢
  • 2022-02-22
  • 2021-05-17
  • 2021-10-11
  • 2021-05-25
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案