python源代码组织和__init.py__ [英] python source code organization and __init.py__

查看:91
本文介绍了python源代码组织和__init.py__的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个python源代码树,其结构如下:

I have a python source tree which is organised as follows:

>folder
   |-> utils
        |-> image.py
        |-> helper.py
        |-> __init__.py

   |-> core
        |-> vf.py
        |-> __init__.py

现在在vf.py中,我有以下一行来导入utils

Now in vf.py, I have the following line to import utils

import utils

然后我做类似的事情:

img = utils.Image()

现在,如果我在utils目录中将__init__.py文件保留为空,则此操作无效,并且出现错误:

Now, if I leave the __init__.py file empty in the utils directory, this does not work and I get an error:

AttributeError: 'module' object has no attribute 'Image'

但是,如果我在utils目录的__init__.py中添加以下行,它将起作用:

However, if I add the following line in __init__.py in the utils directory, it works:

from image import *
from helper import *

因此,我猜测调用顶级脚本时,它将解析此__init__.py文件并从该utils包中导入所有方法和类.但是,我觉得这不是一个好主意,因为我正在执行*导入操作,这可能会污染名称空间.

So, I am guessing that when the top level script is called it parses this __init__.py file and imports all the methods and classes from this utils package. However, I have a feeling this is not such a good idea because I am doing a * import and this might pollute the namespace.

所以,我想知道是否有人可以阐明执行此操作的适当方法,即如果我有并行目录,那么是将类从一个python包导入到另一个python包的好方法(如果确实是__init__.py我怀疑这种方法并不干净.

So, I was wondering if someone can shed some light on the appropriate way to do this i.e. if I have parallel directories, what is a good way to import the classes from one python package to another (if indeed this __init__.py approach is not clean as I suspect).

推荐答案

您是否尝试过使用"img = utils.image.Image()"? 如果在"image.py"文件中定义了"Image"类,那么我认为这会起作用.

Have you tried using "img = utils.image.Image()"? If the "Image" class is defined within the "image.py" file, I think this would work.

这篇关于python源代码组织和__init.py__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆