python - 我们可以将仅包含函数定义的Python文件称为脚本吗?

标签 python scripting

如果 python 中有一个仅包含函数定义的文件,并且我没有在该文件中调用该函数..它是脚本还是模块?例如:-

def func():
    print('Hey')

最佳答案

任何Python文件都是一个模块,你可以import .

根据 python 文档:

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended.

一个空的 python 文件也是一个模块,尽管没用。

任何 python 文件都是一个脚本。

仅包含函数定义的 python 文件是脚本,但它不会执行任何操作。

Python 世界中并没有过多强调这种区别。通常,脚本应该执行一些代码,而模块是由其他脚本导入和执行的函数和类库。

有一个特殊变量 __name__,您可以检查它来判断当前脚本是否直接在 python 解释器中运行(在这种情况下,其值为 "__main__"),或不(即由其他脚本导入),例如:

if __name__ == '__main__':
    # this script is being run directly in the interpreter
    # i.e.  python this_script.py
    #
    # this block will not be executed when this is import'ed

了解更多信息 https://docs.python.org/3/tutorial/modules.html

关于python - 我们可以将仅包含函数定义的Python文件称为脚本吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49879769/

相关文章:

python - Django 中的游标是否在打开的事务中运行?

python - 导入 python-iptables 包时出现 undefined symbol "afinfo" "iptc"

string - Groovy:如何在不转义的情况下在字符串中包含反斜杠?

html - 如何在 Ruby 脚本中备份整个网页(包括图像等)?

python - 在 pandas 中使用日期时间

python - 使用 urllib2 打开的 URL 是否可以限制返回的行数?

java - 创建一个基本上从数据库读取并调用脚本(可能位于不同的 unix 机器上)的 Web 程序,我应该如何开始?

linux - 在行字符串中找到最大数并显示两列 - linux

C# 嵌入脚本解释器时限制命名空间

python - 欧几里得距离的向量化实现