首页 > 解决方案 > Calling variable from external file multiple times in python

问题描述

I'm trying to call variable from external file. And for that I wrote this code,

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

But when I run my code it only calls varible A once and prints the same result. See the output of code,

Random number is 48
Random number is 48
Random number is 48

How can I call variable A from file rand_gen.py with updated value, every time it goes into loop? Please help.

标签: pythonpython-3.xpython-importpython-module

解决方案


如果您将随机值分配给变量,则无论该值是如何获得的,引用该变量都不会更改该值。

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

a # 12
# Wait a little
a # still 12

同样的,当你导入你的模块时,模块代码被执行并且一个值被赋值给A. 除非重新加载模块importlib.reload或您np.random.randint再次调用,否则没有理由A更改值。

您可能想要的是创建A一个返回所需范围内的随机值的函数。

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

推荐阅读