I have a folder:

tastyfood

I have four classes:

chocolate.py
sweets.py
crisps.py
tuna.py

Say I wanted to put the four classes in the folder tastyfood

So I can make importations like:

import tastyfood 

and all the classes are imported rather than each class being imported.

I understand you can use __init__.py and have been reading posts like this But I am unable to find a way to do what I would like.

Any one have suggestions?

有帮助吗?

解决方案

Preamble: This technique can be useful if you have big classes of hundreds lines. If your classes are quite small, you should put them in one single file called tastyfood.py and you'll get the same behaviour, without folders.

If you want to use a folder to classify your classes, you need to have this folder structure:

tastyfood/
    __init__.py
    chocolate.py
    sweets.py
    crisps.py
    tuna.py

example.py  # example file quoted above

and the __init__.py can contains import statement to make your life easier:

from chocolate import Chocolate
from sweets import Sweet
# ... import everything you want in the tastyfood namespace

so these examples, which can be found in example.py, can be valid:

import tastyfood
choco = tastyfood.Chocolate()

from tastyfood import Chocolate
choco = Chocolate()

from tastyfood.chocolate import Chocolate  # still works too
choco = Chocolate()  

其他提示

So all the classes are located in tastyfood/ , correct? You need to put an empty __init__.py file in that folder, along with the other files and you will be able to import them like that.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top