未定义的变量“资源”

时间:2021-01-14 15:27:47

标签: python visual-studio-code

出于某种原因,Visual Studio Code 告诉我我制作的列表不存在。这很奇怪,因为它确实存在!这是我的代码,或者至少是其中的一部分。

class Adventurer:
def __init__(self, name, coins, resources, health):
    # Define class properties here
    name = name
    coins = coins
    resources = resources
    health = 5

    # Begin by querying the user
    userSez = input("Welcome to Astroway!\nType, 'look around' to see your surroundings.\nType 'examine <object>' to examine an object.")
    self.readInput(userSez, 0)

# What did the user say?
def readInput(self, userInput, playLevel):
    if playLevel == 0:
        print("You look around, and find you are in a desert. Around you, there are prickly cacti, a small chest, and a seemingly endless desert wasteland.")    
        userSez = input("Here are your choices of examination:\n\t• cacti\n\t• chest\n")
        self.readInput(userSez, 1)
    if playLevel == 1:
        if userInput == "cacti":
            userSez = input("You reach out to touch one of the cacti. Ouch! You lose 1 heart of health and have 4 left. What next?\n")
            health = health - 1
            self.readInput(userSez, 1)
        elif userInput == "chest":
            userSez = input("You open the chest. Inside, you see a golden key. What could this do? You pick it up. You put it in your inventory. What next?\n")
            resources[0] = "golden_key"
            self.dialogue(0)

所以是的,我希望你能明白我为什么在这里感到困惑。顺便说一句,这是我悬停时出现的错误。 Undefined variable 'resources'pylint(undefined-variable) 当我运行它时,它说我在定义之前使用过它...

2 个答案:

答案 0 :(得分:0)

我认为您没有正确分配属性,您应该指定 self.在分配它们之前

def __init__(self, name, coins, resources, health):
    # Define class properties here
    self.name = name
    self.coins = coins
    self.resources = resources
    self.health = 5 # Btw, why set to 5 if you are getting health in the params?

稍后当您引用这些变量时,例如 resources[0] = "golden_key"
你应该使用 self.resources[0] = "golden_key"

答案 1 :(得分:0)

变量 resources 没有为 readInput 方法内的代码定义。当您在类的构造函数中定义具有该名称的变量时,我假设您的意思是该变量是实例变量。为此,您需要使用 resourcesself 视为类实例的属性:

class Adventurer:
    def __init__(self, name, coins, resources, health):
        ...
        self.resources = resources
        ...
    
    def readInput(self, userInput, playLevel):
        ...
                self.resources[0] = "golden_key"