Python importing variables from other file

大兔子大兔子 提交于 2020-03-22 08:15:45

问题


I have 3 files in the same directory : test1.py , test2.py and init.py.

In test1.py I have this code:

def test_function():
    a = "aaa"

In test2.py I have this code:

from test1 import *


def test_function2():
    print(a)


test_function2()

I can import "test_function" (and call the function) into test2.py but i cannot use the variable "a" in test2.py .

Error : Unresolved reference "a" .

I would like to know if it possible to use "a" inside test2.py .


回答1:


In test1.py you could have a function that returns the value of the variable a

def get_a():
    return a

And when you're in test2.py you can call get_a().

So in test2.py do this to essentially move over the value of a from test1.py.

from test1 import *

a = get_a()

def test_function2():
    print(a)


test_function2()



回答2:


Test1.py

def test_function():
    a = "aaa"
    return a

Test2.py

import test1


def test_function2():
    print(test1.test_function())


test_function2()



回答3:


What are the rules for local and global variables in Python?¶

In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a value anywhere within the function’s body, it’s assumed to be a local unless explicitly declared as global.

So make the variable a global and call test_function() in test1 module so that it makes a as global variable while loading modules

test1.py

def test_function():
  global a
  a = "aaa"

test_function() 

test2.py

from test1 import *

def test_function2():
  print(a)


test_function2()



回答4:


a is only defined in the scope of test_function(). You must define it outside the function and access it using the global keyword. This is what it looks like:

test1.py

a = ""
def test_function():
    global a
    a = "aaa"

test2.py

import test1

def test_function2():
    print(test1.a)

test1.test_function()
test_function2()



回答5:


test1.py's code will be this.

def H():
    global a
    a = "aaa"
H()

and test2.py's code will be this.

import test1 as o
global a
o.H()
print(o.a)

This will allow you to call test one H




回答6:


Your code works perfect (with 'a' defined outside out the test1_function), was able to print 'a'. So try the following : 1. Make sure it is a global variable in test1. 2. Import test1 in an interactive session and find out the bug. 3. Double check the environment setup.

Thanks ! :)



来源:https://stackoverflow.com/questions/56517260/python-importing-variables-from-other-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!