Python import on sub-folders

Viewed 46

It`s been a while since I create my classes and import them to my script, using

from <folder> import <file>

and my file.py looks like this:

class myClass:
    def __init__():

and so on.

However, whenever I want to use this class on my main script, I have to do:

file.myClass()

Is thera a better way so I could use only "myClass()"?

2 Answers

I have recreated the scenario with the following directory structure:

.
├── outer.py
└── some_folder
    └── inner.py

You missed the self in __init__ method:

some_folder/inner.py:

class myClass:
    def __init__(self):
        print("myClass is initiated")

Import the class from the file when you want to directly use the class name.

outer.py:

from some_folder.inner import myClass

some_object = myClass()

Output:

myClass is initiated

Instead of importing the file, you can import the class

from package.module import MyClass
Related