0

I have 2 files:

variables.py:

global var
var = 'test'

and main.py:

import variables

class functionsclass:

    def __init__(self):
        self.testfunction()


    def testfunction(self):
        print(variables.var)

functionsclass()

that does not work, because 'variables.var' doesn't point to 'test'. What do I have to write to access the variable 'var'? I don't want to use a parameter, I just want to access the global variable.

Edit: Sorry. I'm dumb. In my original file I set the wrong var to global, that's why I could not access it.

Cheers

2 Answers2

0

I tried your repro, and it works fine for me both with python2 and python3. The global keyword actually does something different and is not needed, but doesn't hurt.

[Also, FWIW I'd recommand using new-style classes, e.g. class functionsclass(object):]

Community
  • 1
  • 1
lemonhead
  • 5,328
  • 1
  • 13
  • 25
  • Sorry. I'm dumb. In my original file I set the wrong var to global, that's why I could not access it. –  Jun 26 '15 at 20:40
0

I also tried your code and it did work for me :- successfully printed "test". I don't see anything wrong due to which your code is not running.

It might sound dumb, but just check whether the two files (variables.py and main.py) are in the same directory. Because, keeping those two files in separate directory can make it inaccessible.

And, could you please try with the following modifications to your main.py file and check whether this works :-

from variables import var

class functionsclass:

    def __init__(self):
        self.testfunction()


    def testfunction(self):
        print(var)

functionsclass()
Pabitra Pati
  • 457
  • 4
  • 12