python使用另一个文件中的变量 [英] python using variables from another file

查看:207
本文介绍了python使用另一个文件中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新手,正在尝试制作一个简单的随机句子生成器-如何从存储在另一个 .py 文档中的列表中提取随机项目?我正在使用

I'm new and trying to make a simple random sentence generator- How can I pull a random item out of a list that is stored in another .py document? I'm using

random.choice(verb_list) 

从列表中拉出.我如何告诉pythonverb_list在另一个文档中?

to pull from the list. How do I tell python that verb_list is in another document?

此外,了解解决方案背后的原理会很有帮助.我想这就像文件引用"文件桥接"等.

Also it would be helpful to know what the principle behind the solution is called. I imagine it's something like 'file referencing' 'file bridging' etc..

推荐答案

您可以从文件中导入变量:

You can import the variables from the file:

vardata.py

verb_list = [x, y, z]
other_list = [1, 2, 3]
something_else = False

ma​​infile.py

from vardata import verb_list, other_list
import random

print random.choice(verb_list) 

你也可以这样做:

from vardata import *

从该文件导入所有内容.不过要小心.您不想发生名称冲突.

to import everything from that file. Be careful with this though. You don't want to have name collisions.

或者,您可以只导入文件并通过其命名空间访问变量:

Alternatively, you can just import the file and access the variables though its namespace:

import vardata
print vardata.something_else

这篇关于python使用另一个文件中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆