3

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?

2 Answers 2

2

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]

Sign up to request clarification or add additional context in comments.

3 Comments

Yes it works, but as mentioned in the other answer this requires me to run the entire file gui.py from eval.py. If this is the only case then I might have to reconsider teh structure of my program.
As per your program "board" is an instance variable and it will only get create when you will create object of Gui class. If you don't wan't to create instance and just want to access the class variable then board need to be an class variable, not instance. See my updated response of class variable named board set to [5].
Thank you, I come to the conclusion that I need to re-think how I arrange my files/functions/code :)
1

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)

1 Comment

So I need to run the entire file to be able to retrieve the variable?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.