未定义变量“资源”

2024-05-13 01:04:30 发布

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

出于某种原因,VisualStudio代码告诉我,我创建的列表不存在。这很奇怪,因为它确实存在!这是我的代码,至少是其中的一部分

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)当我运行它时,它说我在定义它之前使用过它


Tags: thetonameselfyouinputyourwhat
2条回答

我认为您没有正确分配属性,您应该指定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"

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

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

相关问题 更多 >