Pergunta

A few weeks ago I started learning Python, and I figured the best way to get the hang of it was to jump straight in by making a simple (?) text-based game with the option to save your progress and reload your saved game to continue later.

Since I need it to write a saved object containing several nested lists and dictionaries (rather than a simple string), I went with Pickle.

What's going wrong is this: The save() function works fine on its own, but I later need to access two of the variables within it. For some reason, no matter what I do, save() won't return savePath and saveName; it throws a NameError: savePath/saveName is not defined. I am sure it's something really stupid and obvious that I'm missing, but I can't see what.

P.S. I apologize for the messiness of my code—I haven't really learned how to code efficiently yet.

For this I've cut out the working functions and simplified the classes, but in essence everything else is the same.

http://pastebin.com/x7UPYe5T

Any ideas would be greatly appreciated. I just know I'm going to be kicking myself when I see what the problem is …

Foi útil?

Solução

Fundamentally, your problem is that you're expecting savePath and saveName to be in global scope, where they are only available in the function save(). Your immediate problem will likely be addressed just by including the line:

global saveName, savePath

at the top of the save() function.

This is a good blog post explaining some the differences in variable scope. See also docs to Python global.

That said: global variables are often a sign of problematic design. Especially since you're taking the trouble to return savePath and saveName, a better solution would be to make sure you actually save these values when you return them:

(savePath, saveName) = save()

Here again, you're saving global scope -- but when you wrap that outer level of code in a function, you'll have better encapsulation.

Outras dicas

Use the returned value:

path, name = save()

The local variables inside save() are not visible (do not exist) outside of it.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top