在Python中声明文件末尾的函数 [英] Declare function at end of file in Python

查看:189
本文介绍了在Python中声明文件末尾的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有可能在没有完全定义它的情况下调用一个函数?当尝试这个时,我得到错误: function_name 未定义。我来自C ++的背景,所以这个问题困扰着我。



在工作前声明函数:

$ $ p $ def $ Kerma
returnenergy / mass

print Kerma()

然而,试图调用该函数而不先定义它会带来麻烦:

  print Kerma()

def Kerma():
returnenergy / mass

在C ++中,

我在这里丢失了什么?



  def main() :
print Kerma()

def Kerma():
返回energy / mass

if __name__ =='__main__':
main()

只要你愿意,你可以按你喜欢的顺序编写代码继续在最后调用函数 main


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.

Declaring the function before works:

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"

In C++, you can declare a function after the call once you place its header before it.

Am I missing something here?

解决方案

One way that is sort of idiomatic in Python is writing:

def main():
    print Kerma()

def Kerma():
    return "energy / mass"    

if __name__ == '__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屋!

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