我在尝试用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
德玛西亚99
相关分类