在赋值之前引用的封闭行中分配的局部变量

发布于 2025-01-15 19:56:45 字数 1565 浏览 2 评论 0原文

我有这段代码

health = 12

manager_health = 10 

def manager_boss_fight_used_for_backup():

    sleep(1)
    print("manager health is ",manager_health)
    print("your health is ",health)
    
    sleep(1)

    print("the boss gets first attack")
    manager_boss_damage = random.randint(1,8)
    print(manager_boss_damage)
    print(health)
    health = health - manager_boss_damage
    sleep(1)
    print("the boss did",manager_boss_damage,"damage")
    sleep(1)
    print("your health is now",health)

    if health <= 0:
        sleep(1)
        print("you have died")
        sleep(1)
        print("better luck next time")
        exit()
    sleep(1)
    print("your turn to attack")
    sleep(1)
    heal_or_attack = input("Do you wish to heal or attack?(1/2)")
    if heal_or_attack == "1":
        healing = random.randint(1,7)
        print("you have healed by",healing)
        health = health + healing
        manager_boss_fight_used_for_backup()
    if heal_or_attack == "2":
        print("you attack the boss")
        sleep(1)
        attack_damage = random.randint(1,6)
        print("You did",attack_damage,"damage")
        manager_health = manager_health - attack_damage
        if manager_health <= 0:
            sleep(1)
            print("You have killed the boss")
            sleep(1)

        if manager_health > 0:
            manager_boss_fight_used_for_backup()

,在代码部分中,例如 health = health - manager_boss_damage 它将出错。我摆弄了全局变量和所有这些,但我无法让它工作,所以我来到这里。任何答案表示赞赏!

I have this bit of code

health = 12

manager_health = 10 

def manager_boss_fight_used_for_backup():

    sleep(1)
    print("manager health is ",manager_health)
    print("your health is ",health)
    
    sleep(1)

    print("the boss gets first attack")
    manager_boss_damage = random.randint(1,8)
    print(manager_boss_damage)
    print(health)
    health = health - manager_boss_damage
    sleep(1)
    print("the boss did",manager_boss_damage,"damage")
    sleep(1)
    print("your health is now",health)

    if health <= 0:
        sleep(1)
        print("you have died")
        sleep(1)
        print("better luck next time")
        exit()
    sleep(1)
    print("your turn to attack")
    sleep(1)
    heal_or_attack = input("Do you wish to heal or attack?(1/2)")
    if heal_or_attack == "1":
        healing = random.randint(1,7)
        print("you have healed by",healing)
        health = health + healing
        manager_boss_fight_used_for_backup()
    if heal_or_attack == "2":
        print("you attack the boss")
        sleep(1)
        attack_damage = random.randint(1,6)
        print("You did",attack_damage,"damage")
        manager_health = manager_health - attack_damage
        if manager_health <= 0:
            sleep(1)
            print("You have killed the boss")
            sleep(1)

        if manager_health > 0:
            manager_boss_fight_used_for_backup()

and in the parts of code where for example health = health - manager_boss_damage it will error out. I have fiddled with global variables and all that but I cant get it to work so I came here. Any answers appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

究竟谁懂我的在乎 2025-01-22 19:56:46

也许每个人都会告诉你,使用全局变量是非常糟糕的。为什么不使用 OOP 来代替呢?您可以创建一个 class Manager: 和一个 class Player:,其中 health 作为属性,damage 和 take_damage 作为该类的方法,例如:

class Manager:
def __init__(self):
    self.health = 10
    
def attack(self):
    damage = ramdom.randint(1,8)
    return damage
def take_damage(self, damage):
    self.health -= damage
    if (self.health <= 0):
        self.health = 0
    return self.health

那么 Player 类将是或多或少相同:

class Player:
def __init__(self):
    self.health = 12
    
def attack(self):
    damage = ramdom.randint(1,8)
    return damage
def take_damage(self, damage):
    self.health -= damage
    if (self.health <= 0):
        self.health = 0
    return self.health
def heal(self, amount):
    self.health += amount
    return self.health

当然,理想情况下,您可以创建一个名为“Actor”或“Enemy”的类并从那里派生它们,但现在让我们坚持这一点:

# Instantiate the classes like this:
manager = Manager()
player = Player()
# and then just invoke the methods from the classes:
sleep(1)
print("manager health is ",manager.health)
print("your health is ",player.health)

sleep(1)

print("the boss gets first attack")
damage = manager.Attack()
print("You were hit by {} points".format(damage))
player.take_damage(damage)
print("Your Health is {}".format(player.health))

等等。

As probably everyone will tell you, using global variables is pretty bad. Why don't you use OOP instead? You can create a class Manager: and a class Player: with health as property and damage and take_damage as a method of the class, for example:

class Manager:
def __init__(self):
    self.health = 10
    
def attack(self):
    damage = ramdom.randint(1,8)
    return damage
def take_damage(self, damage):
    self.health -= damage
    if (self.health <= 0):
        self.health = 0
    return self.health

then the Player class would be more or less the same:

class Player:
def __init__(self):
    self.health = 12
    
def attack(self):
    damage = ramdom.randint(1,8)
    return damage
def take_damage(self, damage):
    self.health -= damage
    if (self.health <= 0):
        self.health = 0
    return self.health
def heal(self, amount):
    self.health += amount
    return self.health

Ideally of course, you can create one class called "Actor" or "Enemy" and derive those from there, but let's stick with this for now:

# Instantiate the classes like this:
manager = Manager()
player = Player()
# and then just invoke the methods from the classes:
sleep(1)
print("manager health is ",manager.health)
print("your health is ",player.health)

sleep(1)

print("the boss gets first attack")
damage = manager.Attack()
print("You were hit by {} points".format(damage))
player.take_damage(damage)
print("Your Health is {}".format(player.health))

Etc.

牵你的手,一向走下去 2025-01-22 19:56:46

每当您在 manager_fight_used_for_backup() 函数内对 health 进行赋值时,Python 都会默认尝试分配一个名为 health 的新变量。

最快的修复方法是在函数体的开头使用 global 关键字,以明确您引用的是函数外部的 health 变量

global health

:会告诉 Python 您正在引用函数外部的 health 变量。 但是,最好的解决方案是重构此代码,以便函数不会修改共享的全局状态。

Whenever you make an assignment to health inside the manager_fight_used_for_backup() function, Python attempts to assign a new variable called health by default.

The fastest fix is to use the global keyword at the beginning of the function body, to make it clear that you're referring to the health variable outside of the function:

global health

This will tell Python that you're referring to the health variable outside of the function. However, the best solution is to refactor this code so that functions don't modify a shared global state.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文