使python文件顺序中的函数定义独立 [英] Make function definition in a python file order independent

查看:37
本文介绍了使python文件顺序中的函数定义独立的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Python CGI.我无法在定义之前调用函数.

I use Python CGI. I cannot call a function before it is defined.

在 Oracle PL/SQL 中,有一个前向声明"的技巧:将所有函数命名在顶部,因此定义的顺序无关紧要.

In Oracle PL/SQL there was this trick of "forward declaration": naming all the functions on top so the order of defining doesn't matter.

Python 中也有这样的技巧吗?

Is there such a trick in Python as well?

示例:

def do_something(ds_parameter):
    helper_function(ds_parameter)
    ....

def helper_function(hf_parameter):
    ....

def main():
    do_something(my_value)

main()

大卫是对的,我的例子是错误的.怎么样:

David is right, my example is wrong. What about:

<start of cgi-script>

def do_something(ds_parameter):
    helper_function(ds_parameter) 
    .... 

def print_something(): 
    do_something(my_value) 

print_something() 

def helper_function(hf_parameter): 
    .... 

def main()
    ....

main()

我可以向前声明"脚本顶部的函数吗?

Can I "forward declare" the functions at the top of the script?

推荐答案

在使用任何函数之前必须定义所有函数.

All functions must be defined before any are used.

但是,可以按任何顺序定义函数,只要在任何可执行代码使用函数之前定义所有函数即可.

However, the functions can be defined in any order, as long as all are defined before any executable code uses a function.

您不需要前向声明",因为所有声明都完全相互独立.只要所有声明都在所有可执行代码之前.

You don't need "forward declaration" because all declarations are completely independent of each other. As long as all declarations come before all executable code.

你有问题吗?如果是这样,请发布不起作用的代码.

Are you having a problem? If so, please post the code that doesn't work.

在您的示例中,print_something() 不合适.

In your example, print_something() is out of place.

规则:所有函数都必须在真正起作用的代码之前定义

因此,将所有有效的语句放在最后.

Therefore, put all the statements that do work last.

这篇关于使python文件顺序中的函数定义独立的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆