I have 2 Modules, the first module has class One
with a function which returns a value. The second has 2 classes Two
and Three
with functions. I've imported the class from the first module into the second.
In function i
of Class Two
I've assigned the function x
from class One
to y
. from there I can access returned value by printing y
, the function also returns a variabletype
needed else where in the program.
but also need to access this same variable y
from within function z
in class Three
.
The method I've used in class Three
returns an error. I've tried using getattr
but found no joy. But I believe I may have been using it wrong.
The only other solution I've had is to return y
along with type
. Then assign the function i
in class Two
to pop
in function z
of class Three
. But this calls the function from x
in class One
which means I have to enter another value then it prints multiple unneeded lines.
I've created a mock of this problem to try and find a solution but I'm a little stuck. I need to access the value from y
in function i
of class Two
multiples times in a number of other classes.
Method one:
Module 1: TestOne.py
class One():
def x(self):
Go = input("Please enter value\n")
return Go
Module 2: Test.py
from TestOne import*
class Two():
def i(self):
type = "Move"
y = One.x(self)
print("Test 1: ",y)
return type
class Three():
def z(self):
print("Test 2: ", Two.i.y)
Module 3: TestMain.py
from Test import*
p = Two()
t =Three()
p.i()
t.z()
Error:
PS C:\Users\3com\Python> python testmain.py
Please enter value
Test 1:
Traceback (most recent call last):
File "testmain.py", line 9, in <module>
t.z()
File "C:\Users\3com\Python\Test.py", line 16, in z
print("Test 2: ", Two.i.y)
AttributeError: 'function' object has no attribute 'y'
Method 2:
Module 1: TestOne.py
class One():
def x(self):
Go = input("Please enter value\n")
return Go
Module 2: Test.py
from TestOne import*
class Two():
def i(self):
type = "Move"
y = One.x(self)
print("Test 1: ",y)
return type, y
class Three():
def z(self):
pop = Two.i(self)[1]
print("Test 2: ", pop)
Module 3: TestMain.py:
from Test import*
p = Two()
t =Three()
p.i()
t.z()
Output:
PS C:\Users\3com\Python> python testmain.py
Please enter value
1
Test 1: 1
Please enter value
1
Test 1: 1
Test 2: 1
Edit:
I've done a little digging and have a solution that solves the problem. using global
. But have found a number of articles which say that the use of global
can be somewhat dangerous if not used correctly,
Method 3: Working Solution. Meets desired output.
Module 1: TestOne.py
class One():
def x(self):
Go = input("Please enter value\n")
return Go
Module 2: Test.py
from TestOne import*
class Two():
def i(self):
type = "Move"
global y
y = One.x(self)
print("Test 1: ",y)
return type
class Three():
def z(self):
print("Test 2: ", y)
Module 3: TestMain.py:
from Test import*
p = Two()
t =Three()
p.i()
t.z()
Output:(Desired Output)
PS C:\Users\3com\Python> python testmain.py
Please enter value
1
Test 1: 1
Test 2: 1