简体   繁体   中英

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?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM