Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python import nested class

I'm new to python. This is not my actual case, it's just my curiosity about importing nested class.

So I have a main.py and test.py.

test.py:

class one():
   class two():
      def twodef():
         pass

so in my main.py, I can do 'import test' or 'from test import one'. But I got error when do: 'from test.one import two'.

error : ImportError: No module named one

Anyone can explain this?

like image 325
andio Avatar asked Sep 18 '26 08:09

andio


1 Answers

You can only do from module import name for names that exist in the module's global scope - basically, names that are defined in top-level module code. Names that are defined in lower-level scopes - for example within classes as in your example - are not importable. You need to import the object that contains the name, and access it from there.

from test import one
my_two = one.two()
like image 135
snakecharmerb Avatar answered Sep 20 '26 22:09

snakecharmerb