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
斯蒂芬大帝
浏览 933回答 1
1回答

德玛西亚99

这样用: import game game.SunFlower(0).step() print(game.sunlight)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python