zoukankan      html  css  js  c++  java
  • 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  改了
  • 相关阅读:
    python中使用easygui
    SQL Server: Windows Firewall with Advanced Security
    xxx while the managed IDbConnection interface was being used: Login failed for user xxx
    忽略PyCharm4中特定的警告提示信息
    C#如何生成一个随机种子for Random?
    PSSecurityException之PowerShell权限设置
    如何用CSS进行开发
    为什么不建议用table进行布局
    Batch脚本获取日期SET YEAR=%date:~10,4%
    Java实现邮箱找回密码
  • 原文地址:https://www.cnblogs.com/mingerlcm/p/8400380.html
Copyright © 2011-2022 走看看