将共享功能放在Python程序包中?

问题描述 投票:1回答:1

我正在创建一个供内部使用的python包,它具有一些其他模块共有的内部功能。例如,下面的功能正在其他模块上使用-

def GetLocalImage(WebImage):
  ImageLink = WebImage.get("data-src")
  FileName = ImageLink.split("/")[-1]
  urllib.request.urlretrieve(ImageLink,FileName)
  return(FileName)

您可以看到该功能需要使用urllib。下面是包的文件结构-

formatter
\ __init__.py
\ File1.py    --> It would call GetLocalImage()
\ File2.py    --> It would call GetLocalImage()

我的主程序使用from formatter import *语句。我的问题是-

  1. import urllib和功能的正确位置是什么?
  2. 我需要修改程序包结构吗?
python python-module
1个回答
0
投票

我终于明白了。这是我解决的方法-

  1. 我将共享功能保存到另一个文件common.py
  2. common.py中,我有import urllib.request
  3. File1.pyFile2.py中,我已像from .common import *一样导入
  4. 在主程序中,仅是import formatter
  5. __init__.py文件中,我保留-
from .common import *
from .File1 import *
from .File2 import *

我认为我们可以跳过__init__.py文件(不确定)。希望这对以后的人有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.