在函数内声明的全局变量仍被视为本地变量

时间:2013-12-02 16:14:59

标签: python python-2.7 global-variables local-variables

我正在努力编写程序战舰。我有两个游戏板矩阵:一个用于播放器,一个用于计算机。这些是在main之外定义的,因为我希望它们是全局变量,因为有几个函数操作/读取它们。我使用的是Python 2.6.1。

#create player game board (10x10 matrix filled with zeros)
playerBoard = [[0]*10 for i in range(10)]
#create computer game board (10x10 matrix filled with zeros)
computerBoard = [[0]*10 for i in range(10)]

然后我定义了主要功能。

#define main function
def main():
    global playerBoard
    global computerBoard
    #keepGoing is true
    keepGoing = True
    #while keepGoing is true
    while keepGoing:
        #call main menu function. Set to response.
        response = mainMenu()
        #if response is 1
        if response == "1":
            #begin new game
            #call clearBoards function
            clearBoards()
            #call resetCounters function
            resetCounters()
            #call placeShips function (player)
            playerBoard = placeShips(playerBoard, "player")
            #call placeShips function (computer)
            computerBoard = placeShips(computerBoard, "computer")
            #call guessCycler function
            guessCycler()
        #if response is 2
        if response == "2":
            #keepGoing is false
            keepGoing = False

尽管我在global playerboard内声明了global computerBoardmain但PyScripter仍然说这些是局部变量。我不明白这一点。我怎样才能确保它们是全球性的?

我已经看过的文件:
Using global variables in a function other than the one that created them
Changing global variables within a function
http://www.python-course.eu/global_vs_local_variables.php

1 个答案:

答案 0 :(得分:0)

我绝对认为如果你需要它们是全球性的,你应该重新考虑 - 你没有.-)

便宜的方法是,声明你的东西并将它们作为参数传递给函数

def MyFunc(board1):
    print board1

board1 = "Very weak horse"
MyFunc(board1)    

实现它的真正方法是创建一个类,然后使用self

访问它们
class MySuperClass():
     def __init__(self):
         self.horse = "No way up" 

     def myRealCoolFunc(self):
           print self.horse
 uhhh = MySuperClass()
 uhhh.myRealCoolFunc()