Skip to main content
 首页 » 编程设计

Python:类方法中的变量

2024年10月24日11zfyouxi

我正在学习 Python,并尝试编写一个基于角色热区的伤口系统。这是我写的。不要对我评价太多。

class Character: 
    def __init__ (self, agility, strength, coordination): 
            self.max_agility = 100 
            self.max_strength = 100 
            self.max_coordination = 100 
            self.agility = agility 
            self.strength = strength 
            self.coordination = coordination 
 
    def hit (self, hit_region, wound): 
            self.hit_region = hit_region 
            self.wound = wound 
 
            #Hit Zones 
            l_arm=[] 
            r_arm=[] 
            l_leg=[] 
            r_leg=[] 
            hit_region_list = [l_arm , r_arm, l_leg, r_leg] 
 
 
            #Wound Pretty Names 
            healthy = "Healthy" 
            skin_cut = "Skin Cut" 
            muscle_cut = "Muscle Cut" 
            bone_cut = "Exposed Bone" 
 
            hit_region.append(wound)               
 
john = Character(34, 33, 33) 
 
john.hit(l_arm, skin_cut) 

我希望 skin_cut 输入被识别为“Skin Cut”,然后添加到我定义为列表的 l_arm。但是,我总是收到名称错误(未定义 l_arm)。如果我用“伤口”作为第一个参数重写该方法,则名称错误现在带有未定义的“伤口”。这有点告诉我这是我错过的类(class)结构中的某些内容,但我无法说出是什么。

请您参考如下方法:

我改变了我之前对此的回答。

class Character: 
def __init__ (self, agility, strength, coordination): 
        self.max_agility = 100 
        self.max_strength = 100 
        self.max_coordination = 100 
        self.agility = agility 
        self.strength = strength 
        self.coordination = coordination 
        self.l_arm=[] 
        self.r_arm=[] 
        self.l_leg=[] 
        self.r_leg=[] 
        self.hit_region_list = [self.l_arm , self.r_arm, self.l_leg, self.r_leg] 
        self.healthy = "Healthy" 
        self.skin_cut = "Skin Cut" 
        self.muscle_cut = "Muscle Cut" 
        self.bone_cut = "Exposed Bone" 
 
def hit (self, hit_region, wound): 
        self.hit_region = hit_region 
        self.wound = wound 
        hit_region.append(wound) 
        #Hit Zones 
 
 
 
        #Wound Pretty Names 
 
 
 
 
john = Character(34, 33, 33) 
 
john.hit(john.l_arm,john.skin_cut) 
 
print john.hit_region 
print john.l_arm 

运行上面的代码后我得到了这个输出

output: 
['Skin Cut'] 
['Skin Cut'] 

根据帖子,我认为这就是您想要的。根据您之前的代码,您的声明只能在函数内部访问。现在,您可以通过在构造函数中声明来为特定实例操作数据和这些变量。