簡體   English   中英

Python:類方法中的變量

[英]Python: variables inside class methods

我正在學習 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)。 如果我用“傷口”作為第一個參數重寫方法,則名稱錯誤現在帶有未定義的“傷口”。 這告訴我這是我錯過的課程結構中的某些東西,但我不知道是什么。

您可以在函數中定義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)

這將起作用。

我改變了我之前對此的回答。

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']

根據帖子,我認為這就是您想要的。 根據您之前的代碼,您的聲明只能在函數內部訪問。 現在您可以通過在構造函數中聲明它們來操作特定實例的數據和這些變量。

一旦函數結束,函數內分配的每個局部變量都會被丟棄。 你需要預先准備self. 到這些名稱,以便將它們保存為實例變量,例如self.l_armself.r_arm等。 如果您打算稍后使用這些對象,那么傷口漂亮的名字也是如此。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM