📌  相关文章
📜  如何从Python的另一个文件导入变量?

📅  最后修改于: 2022-05-13 01:54:43.144000             🧑  作者: Mango

如何从Python的另一个文件导入变量?

当代码行数增加时,搜索所需的代码块很麻烦。根据它们的工作来区分代码行是一种很好的做法。这可以通过为不同的工作代码使用单独的文件来完成。众所周知, Python的各种库提供了我们使用简单的 import 访问的各种方法和变量。例如,数学库。如果我们想使用 pi 变量,我们使用 import math 然后是 math.pi。

要从另一个文件导入变量,我们必须从当前程序导入该文件。这将提供对该文件中所有可用方法和变量的访问。

进口声明

通过在其他Python源文件中执行 import 语句,我们可以将任何Python源文件用作模块。当解释器遇到 import 语句时,如果模块存在于搜索路径中,它就会导入该模块。搜索路径是解释器为导入模块而搜索的目录列表。

from import 语句

Python 的 from 语句允许您从模块导入特定属性。

注意:有关更多信息,请参阅Python模块



从其他文件导入变量的不同方法

  • 导入 然后使用 . 访问变量
  • from 导入 并使用变量
  • from import * 然后直接使用变量。

例子:

假设我们有一个名为“swaps.py”的文件。我们必须从另一个名为“calval.py”的文件中从该文件中导入 x 和 y 变量。

Python3
# swaps.py file from which variables to be imported
x = 23
y = 30
  
def swapVal(x, y):
  x,y = y,x
  return x, y


Python3
# calval.py file where to import variables
# import swaps.py file from which variables 
# to be imported
# swaps.py and calval.py files should be in 
# same directory.
import swaps
  
# Import x and y variables using 
# file_name.variable_name notation
new_x = swaps.x
new_y = swaps.y
  
print("x value: ", new_x, "y value:", new_y)
  
# Similarly, import swapVal method from swaps file
x , y = swaps.swapVal(new_x,new_y)
  
print("x value: ", x, "y value:", y)


现在创建第二个Python文件来调用上面代码中的变量:

蟒蛇3

# calval.py file where to import variables
# import swaps.py file from which variables 
# to be imported
# swaps.py and calval.py files should be in 
# same directory.
import swaps
  
# Import x and y variables using 
# file_name.variable_name notation
new_x = swaps.x
new_y = swaps.y
  
print("x value: ", new_x, "y value:", new_y)
  
# Similarly, import swapVal method from swaps file
x , y = swaps.swapVal(new_x,new_y)
  
print("x value: ", x, "y value:", y)

输出:

x value:  23 y value: 30
x value:  30 y value: 23