0

I have 2 files:

fileA.py

and

fileB.py

I am trying to set (change) a variable from fileA from a function within fileB. The variable I'm trying to change is inside of a class (I believe the variable is a Class variable). I tried importing fileA inside of fileB but got errors.

# fileA:
...
class SomeDialog(QDialog):
    my_var = 0
...


# fileB:
...
from fileA import SomeDialog as sd
    def my_func():
        sd.my_var = 5
...

Any help?

shafuq
  • 465
  • 6
  • 20

3 Answers3

1

According to the error you got, you probably have circular import somewhere. It is not related to what you are trying to do with your classes.

See ImportError: Cannot import name X for more details

If that's the case, the only way to solve it is to change your file structures.

Mia
  • 2,466
  • 22
  • 38
  • Even if you're right (and you might be), it doesn't answer the question of how to change a class variable from another file. The answers here are for instance changes. I'm looking for an alternative way of doing this.. – shafuq Mar 24 '18 at 14:36
  • @Mr.Robot The method you are using appear to be right. I tested on my computer and it's working. – Mia Mar 24 '18 at 14:41
0

Your class should look like this:

class SomeDialog(QDialog):
    def __init__(self):
        self.my_var = 0

Then you can access the my_var like this:

SomeDialog.my_var
Gleb Koval
  • 149
  • 1
  • 10
  • This is a large program with thousands of lines. I have that variable used in lots of places and it is defined before init. BTW is your answer for an instance variable? – shafuq Mar 24 '18 at 13:54
  • @Mr.Robot You could make it an instance variable – Gleb Koval Mar 24 '18 at 14:08
  • The thing is I can't. it is important that it stays as a class variable for the program. The value has to always be constant within the different instances. I'm looking for an answer for the way it is shown above. – shafuq Mar 24 '18 at 14:12
  • Ok, sorry then, I cannot help you – Gleb Koval Mar 24 '18 at 14:15
0

Class variables are defined within a class but outside any of the class's methods. Class variables are not used. class variables have the same value across all class instances

A.py

from B import SomeDialog as sd
def my_func():
    print sd.my_var
    sd.my_var = 5
    return sd 
_my_func = my_func()
print _my_func.my_var

B.py

class SomeDialog(object):
    my_var = 0

#output

0
5
Ankit Patidar
  • 467
  • 5
  • 6