鍍金池/ 問答/Python/ python為什么在類的方法內(nèi)修改全局int變量加了global后不報(bào)錯(cuò)但無效?

python為什么在類的方法內(nèi)修改全局int變量加了global后不報(bào)錯(cuò)但無效?

我在嘗試用python寫一個(gè)命令行小游戲,其中有一個(gè)類需要修改一個(gè)全局的int變量,我明明已經(jīng)加了global啊(百度結(jié)果等),代碼也沒有報(bào)錯(cuò),但為什么再訪問變量時(shí)卻沒有被修改?求解答~~
環(huán)境: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
回答
編輯回答
孤星

在開頭處申明全局變量:

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

圖片描述

2018年3月19日 12:08
編輯回答
刮刮樂

這樣用:

import game


game.SunFlower(0).step()
print(game.sunlight)
2017年12月30日 05:11