2

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

1
  • 2
    from <folder.file> import myClass Commented May 27, 2020 at 4:15

2 Answers 2

1

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

4 Comments

@LuccaLemeMarques, yes. One observation is to use CapitalCase for class name. So, standard form of naming myClass is MyClass according to PEP8 style guide. Read more here: python.org/dev/peps/pep-0008/#class-names
Thanks for the notice. I'm used to camelCase, but I'll keep that in mind when it comes to Python! Thanks, regards!
just a simple question, what if I wanted to go down another folder? could I use from <folder1>.<folder2>.<file> import <class> ?
@LuccaLemeMarques, yes, you can import like that.
1

Instead of importing the file, you can import the class

from package.module import MyClass

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.