Lucca Marques
Lucca Marques

Reputation: 121

Python import on sub-folders

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

Upvotes: 2

Views: 66

Answers (2)

arshovon
arshovon

Reputation: 13651

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

Upvotes: 1

bumblebee
bumblebee

Reputation: 1841

Instead of importing the file, you can import the class

from package.module import MyClass

Upvotes: 1

Related Questions