在 Python 中的文件末尾声明函数 [英] Declare function at end of file in Python
问题描述
是否可以在不首先完全定义函数的情况下调用它?尝试此操作时,我收到错误消息:function_name 未定义".我来自 C++ 背景,所以这个问题难倒了我.
Is it possible to call a function without first fully defining it? When attempting this I get the error: "function_name is not defined". I am coming from a C++ background so this issue stumps me.
在工作前声明函数:
def Kerma():
return "energy / mass"
print Kerma()
然而,在没有先定义函数的情况下尝试调用它会带来麻烦:
However, attempting to call the function without first defining it gives trouble:
print Kerma()
def Kerma():
return "energy / mass"
在 C++ 中,你可以在调用之后声明一个函数,只要你把它的头放在它之前.
In C++, you can declare a function after the call once you place its header before it.
我在这里遗漏了什么吗?
Am I missing something here?
推荐答案
一种在 Python 中比较惯用的方式是编写:
One way that is sort of idiomatic in Python is writing:
def main():
print Kerma()
def Kerma():
return "energy / mass"
if __name__ == '__main__':
main()
这允许您按照您喜欢的顺序编写代码,只要您在末尾继续调用函数 main
.
This allows you to write you code in the order you like as long as you keep calling the function main
at the end.
这篇关于在 Python 中的文件末尾声明函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!