在Python包中的何处放置共享函数?

2024-09-29 23:23:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个供内部使用的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. 我需要修改包结构吗

Tags: 模块pyimport功能formatteriturllibcall
1条回答
网友
1楼 · 发布于 2024-09-29 23:23:55

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

  1. 我将共享函数保存到另一个文件common.py
  2. common.py中,我有import urllib.request
  3. 在{}&File2.py,我像from .common import *一样导入
  4. 在主程序中,它只是import formatter
  5. __init__.py文件中,我保存了-
from .common import *
from .File1 import *
from .File2 import *

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

相关问题 更多 >

    热门问题