在Python中导入变量,新主题因为旧主题对我不起作用 [英] Importing variables in Python, new topic as the old one does not work for me

查看:82
本文介绍了在Python中导入变量,新主题因为旧主题对我不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读以下链接的所有答案:是从另一个文件导入变量吗? 我已经尝试过他们说的话,通过点击,将变量从一个文件导入到另一个文件:

I have read all of the answers of the following link : Importing variables from another file? I have tried what they say, to import my variables from one file to another by tapping :

from file1 import *

from file1 import var1

不幸的是,它不能按预期工作,因为我不是仅导入变量,而是整个文件1.那不是目的(我真的只想要var1,脚本相当大),所以我想知道我是否是唯一注意到这种行为的人,因为那里的每个人都对答案感到满意.

Unfortunately it does not work as intented because I am not importing the variable only but the whole file1. That is not the purpose (I really only want var1, the script is rather big) so I am wondering if I am the only one noticing this behaviour as everybody there looks satisfied with the answer.

感谢您的帮助.

推荐答案

您很可能在文件中运行了一些代码,这些代码要么全部在已定义的函数之外,要么在运行时自动运行的主函数中运行(因此导入时也是如此.

You most likely have some code running in your file which is either outside of defined functions all together or in a main function that is run automaticalls upon running (and thus also when imported.

换句话说,如果file1看起来像这样:

In other words if file1 looks like this:

var1 = 'hello'

def printHello():
    print var1

然后编写from file1 import var1只会导入该内容.另一方面,如果file1看起来像这样:

then writing from file1 import var1 will only import that. If on the other hand file1 looks like this:

var1 = 'hello'

print var1

它将导入var1,但还会打印"hello".

It will import var1 but also print 'hello'.

这篇关于在Python中导入变量,新主题因为旧主题对我不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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