Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

Make function definition in a python file order independent

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

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.

Is there such a trick in Python as well?

example:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


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

The rule: All functions must be defined before any code that does real work

Therefore, put all the statements that do work last.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...