如何导入其他Python文件?
要在代码中使用任何程序包,必须首先使其可访问。您必须导入它。在定义之前,您不能在Python中使用任何东西。有些东西是内置的,例如基本类型(如int,float等)都可以在需要时使用。但是,您要做的大多数事情都需要做更多。例如,如果要计算1弧度的余弦值,并且运行math.cos,则会得到NameError,因为未定义math。
示例
您需要告诉python首先在代码中导入该模块,以便您可以使用它。
>>> math.cos(0) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'math' is not defined >>> import math >>> math.cos(0) 1.0
如果您要导入自己的python文件,则可以使用import语句,如下所示:
>>> import my_file # assuming you have the file, my_file.py in the current directory. # For files in other directories, provide path to that file, absolute or relative.