在python中多次从外部文件调用变量

在python中多次从外部文件调用变量,python,python-3.x,python-import,python-module,Python,Python 3.x,Python Import,Python Module,我正在尝试从外部文件调用变量。为此我写了这段代码 count = 1 while (count <= 3): # I want to iterate this line # rand_gen is the python file # A is the varialbe in rand_gen.py # Having this expression A = np.random.randint(1, 100) from rand_gen import A

我正在尝试从外部文件调用变量。为此我写了这段代码

count = 1
while (count <= 3):
   # I want to iterate this line
   # rand_gen is the python file
   # A is the varialbe in rand_gen.py
   # Having this expression A = np.random.randint(1, 100)
   from rand_gen import A

   print('Random number is ' + str(A))
   count = count + 1

如何从文件
rand_gen.py
调用变量
A
,每次它进入循环时都使用更新的值?请提供帮助。

如果将随机值指定给变量,则引用该变量不会使值发生更改,无论该值是如何获得的

a = np.random.randint(1, 100)

a # 12
# Wait a little
a # still 12
同样,当您导入模块时,执行模块代码,并为
a
分配一个值。除非使用
importlib.reload
重新加载模块,或者再次调用
np.random.randint
,否则
A
没有理由更改值

您可能想要的是使
成为一个
函数,返回所需范围内的随机值

# In the rand_gen module
def A():
    return np.random.randint(1, 100)

在python中,
import
不是这样工作的。导入后,
模块
缓存在
系统模块
中,作为
模块名称和模块对象对。当您再次尝试导入相同的
模块
时,只需将已缓存的值取回来即可。但是
sys.modules
是可写的,删除
键将导致
python
检查模块并再次加载

尽管Olivier的答案是正确的方法,但为了理解
import
,您可以尝试以下方法:

import sys       # Import sys module

count = 1
while (count <= 3):
   # I want to iterate this line
   # rand_gen is the python file
   # A is the varialbe in rand_gen.py
   # Having this expression A = np.random.randint(1, 100)
   if 'rand_gen' in sys.modules:   # Check if "rand_gen" is cached
       sys.modules.pop('my_rand')  # If yes, remove it
   from my_rand import A           # Import now

   print('Random number is ' + str(A))
   count = count + 1

建议您阅读官方Python文档,以便彻底理解。

读取值
A
不会更改该值,它是在您第一次加载模块时分配的。为什么不直接调用
np.random.randint(1100)
。您可以强制它,但它非常不直观,例如,
import-importlib;importlib.reload(rand_gen)
或者,使
A
成为一个函数并调用它,例如
def A():返回np.random.randint(1100)
然后
str(A())
每次都会给你一个不同的值。谢谢@akshat这是我想要的。因为我的实际代码是不同的,这个方法适用于这一点。再次感谢。很高兴能帮上忙:)
import sys       # Import sys module

count = 1
while (count <= 3):
   # I want to iterate this line
   # rand_gen is the python file
   # A is the varialbe in rand_gen.py
   # Having this expression A = np.random.randint(1, 100)
   if 'rand_gen' in sys.modules:   # Check if "rand_gen" is cached
       sys.modules.pop('my_rand')  # If yes, remove it
   from my_rand import A           # Import now

   print('Random number is ' + str(A))
   count = count + 1
Random number is 6754
Random number is 963
Random number is 8825