I am trying to import a specific class variable from another file in Python 3. However, I am not sure how to do this corretly or even make it to work at all.
File "gui.py"
class Gui:
def __init__(self):
self.board = [0]
def run(self):
self.board = [2]
if __name__ == '__main__':
Gui().run()
In file eval.py below I want to use the updated variable self.board = [2] from gui.py. I tried below code examples but got the error "AttributeError: type object 'Gui' has no attribute 'board'" in both cases.
File "eval.py"
from gui import Gui
board = Gui.board
board = __import__('gui').Gui.board
I also tried to remove the name=main thing from gui.py but as expected it only made gui.py run its code and then I got the same error as previously.
How do I access the variable self.board from Gui.run() from gui.py in eval.py in the best and most efficient possible way?
Try this:
test.py
class Gui:
def __init__(self):
self.board = [0]
def run(self):
self.board = [2]
test1.py
from test import Gui
boardObj = Gui()
boardObj.run()
print(boardObj.board)
Run test.py and you will be able to access board from test1.py file and it will be modified to [2].
Example of class variable:
test.py
class Gui:
board = [5]
def __init__(self):
self.board = [0]
def run(self):
self.board = [2]
test1.py
from test import Gui
print(Gui.board)
obj = Gui()
obj.run()
print(obj.board)
Gui.board(class variable) will give you ans [5] and obj.board(instance variable) will give you ans [2]
This has nothing to do with importing.
board is an instance variable, not a class one. You need an instance of Gui:
gui = Gui()
gui.run()
print(gui.board)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With