3

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?

0

3 Answers 3

3

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

Comments

0

You could do the following:

from test import one

two_object = one.two()
two_object.twodef()

Comments

0

inside test.py

class One:
    class Two:
        @staticmethod
        def twodef():
          print("twodef")

My main logic:

from test import One
two_obj = One.Two
two_obj.twodef()

Remove the parenthesis at the end of class definition.

Coding standards:

Always declare your class names in upper camel case (class one => class One).

For more about scope

Preference:

And if you have a single class inside python file, always name that file in that class name but in lower camel case. (test.py => one.py). I have thought this as a standard earlier, but seems its practiced widely. I would use this because, if then project size grew and if you end up having a lot of classes and modules, it's logical and easy to access, rather than visiting the module to find the class name. Ref1 Ref2

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.