如何导入其他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.热门推荐
10 恋爱祝福语大全简短搞笑
11 2026猪年祝福语简短语
12 新娘对伴娘祝福语简短
13 年后祝福语简短走心
14 2026新年祝福语简短语
15 入学校简短祝福语
16 朋友祝福语两字简短
17 汤姆猫祝福语简短霸气
18 亲戚送行祝福语简短精辟