shafuq
shafuq

Reputation: 465

Set a variable from a class within a different file

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?

Upvotes: 0

Views: 36

Answers (3)

Ankit Patidar
Ankit Patidar

Reputation: 477

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

Upvotes: 0

Mia
Mia

Reputation: 2676

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.

Upvotes: 1

Gleb Koval
Gleb Koval

Reputation: 149

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

Upvotes: 0

Related Questions