将子文件夹python文件导入为文件夹(包),而不是模块

时间:2018-01-23 06:35:35

标签: python-3.x python-import

是否可以在gui.settings.load()之后调用函数from ... import gui?我正在尝试设置这样的文件夹。

main.py
gui/
    __init__.py
    settings.py

并在settings.py

def load():
    print('Hello') 

在main.py

import gui

gui.settings.load()

我是否必须弄乱__init__.py

现在,我必须将文件命名为guiSettings.py,我想让它更简单。

2 个答案:

答案 0 :(得分:0)

根据你的定义加载不是一个函数它是一个类所以你不能这样调用(类是要实例化你应该审查OOP cocepts)。如果你想调用函数"加载"你应该把它定义为:

def load(parameters):
  #function body
  #optional return statement

并与目录作为模块e.i进行交互。使用点符号。该目录应包含__init__.py文件。根据文件:

  

包是一种使用构造Python模块命名空间的方法   “虚线模块名称”。例如,模块名称A.B表示a   名为A的包中名为B的子模块。

此外:

  

需要__init__.py个文件才能让Python对待   目录包含包;

所以在你的情况下你应该在outter gui目录和内部gui目录中定义"__init__.py"(可能为空)。然后在设置模块中,您可以像上面一样定义加载功能。您可以在此处阅读有关包和模块的更多信息https://www.tutorialspoint.com/python/python_modules.htm

答案 1 :(得分:0)

如果我真的想打电话给gui.settings.load(),我可能会像这样构建我的目录。

main.py
src/
    __init__.py
    gui/
        __init__.py
        settings.py

main.py

from src import *

gui.settings.load()

src/__init__.py

from . import gui

src/gui/__init__.py

from . import settings

src/gui/settings.py中仍与上述相同。

似乎将__all__ = ['gui']__all__ = ['settings']放在相应的__init__.py中并不起作用,除非我误解了__all__的工作方式。

此外,在这种情况下,__init__.py不能为空。

此外,import *中只有from main.py而不是console.log('up and running'); var cards = [ { rank: 'queen', suit: 'hearts', cardImage: 'images/queen-of-hearts.png', }, { rank: 'queen', suit: 'diamonds', cardImage: 'images/queen-of-diamonds.png', }, { rank: 'king', suit: 'hearts', cardImage: 'images/king-of-hearts.png', }, { rank: 'king', suit: 'diamonds', cardImage: 'images/king-of-diamonds.png', } ]; var cardsInPlay = []; var checkForMatch = function() { // 2 - Are there two flipped cards? // No, because there are no cards in play yet if (cardsInPlay.length === 2) checkForMatch(); // 3 - I think that 'if' is missing a curly brace! // So the follow code runs: // 4 - undefined === undefined if (cardsInPlay[0] === cardsInPlay[1]) { // 5 - Match! alert('You found a match!'); } else { alert('Sorry, try again.'); } }; // 1 - This runs before any cards are flipped checkForMatch(); var flipCard = function(cardId) { console.log("User flipped " + cards[cardId].rank); console.log(cards[cardId].cardImage); console.log(cards[cardId].suit); cardsInPlay.push(cards[cardId].rank); } flipCard(0); flipCard(2);

相关问题