2
votes

I have the following problem. I want to edit the variables of the class from the module I just imported. I can only find the reverse way. To edit module from main. I want the following:

main.py:

class A:
     MyVar = 7
import a
print(MyVar) #I want to get 4

a.py:

 A.MyVar = 4

When executing main.py I get 'NameError: name A is not defined'.

1
A is not in a.py's namespace. - Stephen Rauch
Not in main's namespace? Then how can I add it there? - N. Boumakis
You are going to encounter other problems in this situation - juanpa.arrivillaga

1 Answers

1
votes

I think you should do something like this:

main.py:

if __name__ == '__main__':

    from a import A

    print(A.my_var) # 7

    A.my_var = 4

    print(A.my_var) # 4

a.py:

class A(object):
    my_var = 7

or

main.py:

if __name__ == '__main__':

    from a import A

    a_obj = A()

    print(a_obj.my_var) # 7

    a_obj.my_var = 4

    print(a_obj.my_var) # 4

a.py:

class A(object):
    def __init__(self):
        self.my_var = 7