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  改了
  • 相关阅读:
    liunx基本命令
    liunx—awk
    python—__name__
    python—url路径拼接/编码
    python—__init__作用
    单元测试
    2、选择排序
    1、算法简介
    在命令行输入python出现“Warning:This Python interpreter is in a conda environment, but the environment has not been activated. Libraries may fail to load. To activate this environment please see https://conda.
    如何明确区分代码中的1和l
  • 原文地址:https://www.cnblogs.com/mingerlcm/p/8400380.html
Copyright © 2011-2022 走看看