1 Antwort
+ 1
I faced this question on other programming site? I represent the overall..
How do I prototype a method in a generic python program similar to C++?
//PROTOTYPE do python protoyping writeHello()
//GIVES ERROR AS IT WAS NOT DEFINED YET
def writeHello():
print "Hello"
Solution:
Python looks up globals at runtime; this means that when you use writeHello the object is looked up there and then. The object does not need to exist at compile time, but does need to exist at runtime.
In C++ you need to prototype to allow two functions to depend on one another; the compiler then can work out that you are using the second, later-defined function. But because Python looks up the second function at runtime instead, no such forward definition is needed.
To illustrate with an example:
def foo(arg):
if not arg:
return bar()
def bar(arg=None):
if arg is not None:
return foo(arg)
Here, both foo and bar are looked up as globals when the functions are called, and you do not need a forward declaration of bar() for Python to compile foo()successfully.