Reputation: 4122
I have two .py files. The first contains a class. The second imports that class and it's function, then attempts to reference variables within that function locally as so:
File B:
class master_test():
def __init__(self):
pass
def func_one(self, var1, var2, var3):
if var1 == 1:
print('first')
else:
print('second')
if var2 == 2:
print('first')
else:
print('second')
if var3 == 3:
print('first')
else:
print('second')
return var1, var2, var3
File A:
import sys
sys.path.append('G:\Python36\Test\Folder_1')
from Test1 import *
test_var = master_test()
test_var.func_one(6,7,8)
temp = var1
print(temp)
However, when I run file A, I get the following error:
Traceback (most recent call last):
File "G:/Python36/Test/Master.py", line 8, in <module>
temp = var1
NameError: name 'var1' is not defined
What am I doing wrong?
Thanks
Upvotes: 0
Views: 49
Reputation: 1161
var1 is not a module-level variable in Test1.py. It belongs to a function func_one
of a class master_test
. A class is not an object, a class is a template to create objects. You could have multiple master_test
objects.
Imagine you had this code:
from Test1 import master_test
test_var1 = master_test()
test_var2 = master_test()
test_var1.func_one(6,7,8)
test_var2.func_one(2,3,4)
Now if you wanted to reference var1, which one do you even want? The one from test_var1 or from test_var2? You need to re-think how you're passing around data. The correct way to pass data back from functions is to use a return
statement.
temp, _, _ = test_var1.func_one(6, 7, 8)
This will set temp equal to var1, which is 6.
Upvotes: 0
Reputation: 780851
var1
is a local variable, you can't access it outside the function.
But it returns it, so you can assign the result.
x, y, z = test_var.func_one(6, 7, 8)
print(x)
Upvotes: 3