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?

1
  • 1
    Try replacing global var_1_global by from file_2 import var_1_global in method set_message. Commented May 18, 2022 at 7:19

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.