python - 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.
解决方案
如果您将随机值分配给变量,则无论该值是如何获得的,引用该变量都不会更改该值。
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)
推荐阅读
- javascript - Vue.js 定义 lodash 需要 "this._"
- javascript - MaterialUI 自动完成 - 选择选项时避免清除输入文本过滤器
- python - 从基于列的数组中返回多数加权投票
- javascript - 如何在 Formik 'onSubmit' 函数中正确地 'useState'?
- python - How to get lowercase results from the input and compare them to other results and differentiate them from other similar results?
- xaml - Xamarin 表单,XAML 中的动态 ScrollView
- flutter - Flutter 如何在特定屏幕上强制使用暗模式
- android - Android:带有 Volley 的 HTTP 请求无法使用参数调用
- javascript - 使外部 JS 脚本中的元素可点击
- angular - Electron Angular 如何使用本地存储