简体   繁体   English

在Python中实现函数的前向声明

[英]Implementing forward declarations for functions in Python

Is it possible to declare functions and implement them separately in python ? 是否有可能声明函数并在python中单独实现它们? I mean something like in C : 我的意思是在C中:

void foo();



void foo() 
{

}

C forward declarations are used to work around dependency problems. C前向声明用于解决依赖性问题。 Function foo is used by function bar , and foo needs bar to exist before you can declare it: 功能foo由功能使用bar ,和foo需要bar存在,然后才能将它声明:

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

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

won't compile because foo hasn't been declared yet; 将不会编译,因为还没有声明foo ; void foo(); is the C spelling for I know what I am doing, compiler, accept that foo will exist later . 是C拼写我知道我在做什么,编译器,接受foo以后会存在

There are no such dependency problems in Python, as global names are looked up at runtime; Python中没有这样的依赖性问题,因为全局名称在运行时被查找; 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. 因为barfoo在运行时被解析了。

If your script is standalone you can use __name__=='__main__' to circumvent your problem with forward declaration read more . 如果你的脚本是独立的,你可以使用__name__=='__main__' ,以规避与向前声明您的问题更多

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 . 我不熟悉C Judging by the comments you've already gotten, seems like you're trying to solve a problem that doesn't exist in Python. 从您已经得到的评论来看,似乎您正在尝试解决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. 然后可以在子类( 可选 )中实现这些方法,而不是必须实现的抽象方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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