简体   繁体   中英

Implementing forward declarations for functions in Python

Is it possible to declare functions and implement them separately in python ? I mean something like in C :

void foo();



void foo() 
{

}

C forward declarations are used to work around dependency problems. Function foo is used by function bar , and foo needs bar to exist before you can declare it:

void bar()
{
    if (condition) { foo(); }
}

void foo() 
{
    if (condition) { bar(); }
}

won't compile because foo hasn't been declared yet; void foo(); is the C spelling for I know what I am doing, compiler, accept that foo will exist later .

There are no such dependency problems in Python, as global names are looked up at runtime; they don't have to yet exist at compile time.

In other words, this just works :

def bar():
    if condition: foo()

def foo():
    if condition: bar()

because bar and foo are resolved at runtime.

If your script is standalone you can use __name__=='__main__' to circumvent your problem with forward declaration read more .

Note that this is not really an answer to your question but a work around. Consider the following script as an example.

def main():
    bar()

def bar(): 
    print "Hello World"

if __name__=="__main__":
   main() # can be any function not necessarily "main"

I'm not familiar with C . Judging by the comments you've already gotten, seems like you're trying to solve a problem that doesn't exist in Python.

The closest thing I can think of for what you're asking is this:

def foo(): pass

This is used sometimes for testing purposes when laying out a class, for example, and you wish it to run smoothly even if you haven't written the code for a particular function yet.

However, there is another use for it. If you're trying to create the template method pattern, callback functions declared in the baseclass could take the following form :

def callback(): pass

These methods could then be implemented in subclasses ( optionally ), as opposed to abstract methods, which must be implemented.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM