I am confused about the below given code in Python where a function has been called before its definition. Is it possible? Is it because the function does not return a value?

from Circle import Circle

def main():
    myCircle = Circle()
    n = 5
    printAreas(myCircle, n) #The function is called here

def printAreas(c, times):
    xxxx
    xxxx

main()
有帮助吗?

解决方案

What happens in your program:

  1. main is defined, with a reference to printAreas in its body—note, this is just a reference, not a call
  2. printAreas is defined
  3. main is invoked
  4. main calls printAreas.

So all is good—you are allowed to reference any names you want at any time you want, as long as you ensure these names will have been defined (bound to a value) by the time the code containing the reference is executed:

def foo():
    print bar  # reference to as-of-yet non-existent bar

# calling foo here would be an error

bar = 3

foo()  # prints 3

其他提示

Python will first parse your file, register all function, variables, etc into the global namespace. It will then call the main function, which will then call printAreas. At the time, both functions are in your script namespace, and hence perfectly accessible.

The thing that is confusing you is just the reading order.

You are calling main at the end of your program. This allows the interpreter to load up all your functions and then start your main function.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top