问题
In other languages I often do something like this:
someFunc()
someFunc() {
// This is my function
}
This way I can stack all my functions lower in the file, but make the function calls at the top. Now I have a nice overview of everything that's happening.
However, when I did this in Python 3 in Spyder, I got the warning that Undefined name: 'myfunc'
my_func("Some string")
def my_func(some_var):
print(some_var)
The code works fine, but I'm not sure what best practice here. Are there any negative impacts caused by my method? Or is it merely a guideline to have your functions before you call them?
The code I set above does work for me. Why is that? I'm running Python 3.4.3 with Anaconda. What's different about my version? Or is it because I run it in Spyder?
Edit: so apparently Spyder works in mysterious ways. First I had the call after the definition, which worked, then I swapped the call to the first line and it still worked. Spyder seems to cache functions or at least not flushing them out. (Though I'm not sure if it's Spyder that's doing the caching or Python itself. I'm assuming Python.) For any newbies out there wondering about this: solution is to restart your programme and/or Python service.
回答1:
From my own comment:
Try restarting your interpreter, maybe you've accidentally defined
my_func
earlier on already?
And another one:
The code, as is, doesn't work. You've most likely defined
my_func
earlier on already in the same REPL session, try restarting your IDLE or w/e you're using. The code doesn't work unless you've done something else already.
As it turned out, this was the issue, and your IDE was somehow "caching" the function definition from earlier on during that session.
In general, when you usually run into weird problems that make no sense and shouldn't be there in the first place (such as this), you should restart your IDE. More often than not it solves the problem, and the issue was just something silly like caching.
Also, when using CPython, the default, most widely used implementation of the Python programming language, you're using Python as an interpreted language, thus your interpreter is going through the code in order from top to bottom. This is why you normally can't call a function before defining it in Python.
回答2:
That doesn't work in the standard Python build, because the file is parsed in order. The other languages you refer to are compiled (in the traditional sense, not JIT or anything), so the order doesn't matter, but Python requires the first things to come first.
Define/assign/create/etc. things before using them.
来源:https://stackoverflow.com/questions/32255580/why-can-i-call-a-function-before-defining-it-with-only-a-warning