全局变量。我做错了什么我不知道是什么

时间:2014-07-16 18:31:00

标签: python-2.7 global

我有一堂课,我试图从中获取文字。现在所有这些都写在一个文件中。我还没有把任何东西搬到另一个档案。

这是我的评论代码。

prompt = '> ' #This was here for my game. I just used it as a test for def thing()

def thing():
    global prompt #global works like it should here.
    paint = prompt #changed so I can print it but I'm sure I could have just skipped this.
    return paint #I could have probably put prompt here without the previous line just fine.

print thing() #test looks good.

text = "" # I added this to see if I could figure out what's going on. 
# I don't get an error when this is here but it's not what I'm looking to do.

class grid_object:
    x = 1 # x of grid
    y = 1 # y of grid
    player_here = '0' #0 = the player was never here. - = the player was here. X = the player is here.
    text = " " # I change this with another function below. This is what I'm trying to access.
    been_here_text = " " # I change this with another function below. 
    been_here_before_bool = False #This gets toggled elsewhere.

    def text_to_type(self):
        global text #So this will point to the text up top but what I want is the text in the class.
        #How do I get the text I want? That is my question to you guys. 
        to_print = text #Probably don't need this like the test above. 
        return to_print

如何获取我想要访问的text

1 个答案:

答案 0 :(得分:1)

您未正确使用class。这样做:

class grid_object(object): # inherit from object for new-style classes
    def __init__(self): # when you instantiate the class, this function runs
        self.x, self.y = 1, 1
        self.player_here = '0'
        self.text = " "
        self.been_here_text = " "
        self.been_here_before_bool = False
    def text_to_type(self):
        return self.text
        # this whole function is silly, just reference
        # self.text any time you would do grid_object().text_to_type()

然后你可以这样做:

>>> obj = grid_object()
>>> obj.text
" "
>>> obj.x
1
>>> obj.y
1
>>> obj.been_here_before_bool
False

这里的诀窍是你要修改一个OBJECT而不是类本身。这就是为什么在类定义中所有内容都在self.之前的原因。你不再谈论这个课程,你正在谈论属于该实例的事情。