2

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'.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135

1 Answers1

1

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
KelvinS
  • 2,870
  • 8
  • 34
  • 67