Python:类方法中的变量

2024-06-13 08:02:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习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\u arm未定义)。“如果伤口”被定义为“伤口”的话,我会用“伤口”来重写。这说明我错过了这个课程,但我不知道是什么。在


Tags: selfdefregionmaxstrengtharmskincut
3条回答

我改变了之前的回答。在

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

运行上述代码后,我得到了这个输出

^{pr2}$

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

函数中分配的每个局部变量在函数结束时都会被丢弃。您需要在这些名称前面加上self.,以便将它们保存为实例变量,例如self.l_armself.r_arm,等等。如果你打算以后使用这些对象的话,伤口漂亮的名字也是一样。在

您可以在函数中定义l_arm,并且它只对该函数是局部的。它只具有功能范围。只能在函数内部访问。在

您试图访问l_arm外部函数,这会导致错误,l_arm未定义。在

如果要访问函数外部的所有变量,可以在class上面定义它

#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"

class Character:
    ...
    ...
    ...

john = Character(34, 33, 33)

john.hit(l_arm, skin_cut)

这会有用的。在

相关问题 更多 >