andio
andio

Reputation: 1778

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?

Upvotes: 3

Views: 2570

Answers (3)

Mitty
Mitty

Reputation: 340

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

Upvotes: 0

snakecharmerb
snakecharmerb

Reputation: 55903

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()

Upvotes: 3

Artur Padalianchyk
Artur Padalianchyk

Reputation: 304

You could do the following:

from test import one

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

Upvotes: 0

Related Questions