Scott
Scott

Reputation: 163

How can you a access a superclass from inside a subclass in different a file?

I'm trying to create an instance of a subclass in a script called main.py. The subclass and its associated superclass each live in separate files in a subdirectory. The file structure is as follows:

In main.py I can load the protocol superclass using from protocols.protocol import protocol Using this approach I can generate an instance of the superclass without issue.

However, when I next try to load the MovingBar subclass using from protocols.MovingBar import MovingBar I get the following error

NameError: name 'protocol' is not defined

Presumably, this is because I have a reference to protocol in the class def of MovingBar as follows:

class MovingBar(protocol):
    def __init__(self):
        super().__init__()

I'm not sure why python recognizes a reference to protocol in the main.py file, but not when it's in the MovingBar file. Is there a way to import protocol such that it can be seen when I'm subsequently importing MovingBar?

Upvotes: 0

Views: 78

Answers (1)

Tim Roberts
Tim Roberts

Reputation: 54726

You need from protocol import protocol in your MovingBar.py. Modules do not inherit the global environment of their callers.

Upvotes: 1

Related Questions