python为什么在类的方法内修改全局int变量加了global后不报错但无效?

我在尝试用python写一个命令行小游戏,其中有一个类需要修改一个全局的int变量,我明明已经加了global啊(百度结果等),代码也没有报错,但为什么再访问变量时却没有被修改?求解答~~
环境:mac+python3.6+pycharm+ipython
我的代码:

# python代码
obj = {'s': []}
sunlight = 0


class GameObject:
    indicating_char = ''

    def __init__(self, pos):
        self.pos = pos
        obj[self.indicating_char].append(self)

    def __str__(self):
        return self.indicating_char

    def step(self): pass


class Sunflower(GameObject):
    def __init__(self, pos):
        self.indicating_char = 's'
        super().__init__(pos)

    def step(self):
        print('executing')
        global sunlight
        sunlight += 50

# ipython
In [1]: from game import *

In [2]: Sunflower(0).step()
executing

In [3]: sunlight
Out[3]: 0
阅读 4.8k
2 个回答

这样用:

import game


game.SunFlower(0).step()
print(game.sunlight)

在开头处申明全局变量:

obj = {'s': []}
global sunlight
sunlight = 0

图片描述

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题