0

So I have this code (parent class in file_1.py):

class do_something():    
    def __init__(self, day, month, year):
        self.day = day
        self.month = month
        self.year = year
        
    def set_message(self, s): 
        global var_1_global
        self.var_1 = var_1_global 

which is inherited by child class (in file_2.py) like that:

from file_1 import do_something
var_1_global = ""

class child_do_something(...,do_something,..):
    ...

The code is much larger, but I cannot put it in stackoverflow. I put only the key code. So the error I get is this:

NameError: name 'var_1_global ' is not defined

and shows the line in parent class (file_1.py) and more specifically:

self.var_1 = var_1_global 

I have searched and found this: python derived class call a global variable which initialized in superclass which does not help. Any idea what I am missing here and how to fix it?

just_learning
  • 413
  • 2
  • 11
  • 24
  • 1
    Try replacing `global var_1_global` by `from file_2 import var_1_global` in method `set_message`. – qouify May 18 '22 at 07:19

1 Answers1

1

Your code would be correct if var_1_global was defined in file_1.py. Here your global var_1_global statement has no effect since var_1_global is not in your global scope. Since it belongs to another file you have to import it from file_2.

However since file_2 already imports do_something from file_1 at the top level. Putting this:

from file_2 import var_1_global

at the top level of file_1 would result in a cyclic import. Therefore you have to perform this import in method set_message to avoid that cycle issue. A solution is therefore to change:

    def set_message(self, s): 
        global var_1_global
        self.var_1 = var_1_global

by:

    def set_message(self, s): 
        from file_2 import var_1_global
        self.var_1 = var_1_global
qouify
  • 3,698
  • 2
  • 15
  • 26