创建python库:如何编写

2024-09-30 03:24:22 发布

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

我编写了一个小Python库,目前托管在BitBucket。如您所见,该库名为pygpstools,它由5个文件组成:

  • gpstime.py→一个类
  • satellite.py→一个类
  • geodesy.py→一个具有某些大地测量方法的模块
  • almanacs.py→一个带有年鉴方法的模块
  • constants.py→一些常量

我想用自述中写的那样。例如:

from pygpstools import GPSTime
GPSTime(wn=1751, tow=314880)

或者:

^{pr2}$

但是在用命令python setup.py install安装了我的库之后,当我试图访问GPSTime类时,我得到了ImportError。在

我想问题出在__init__.py文件。当我在pythonirc频道询问这个问题时,有人告诉我,让它空着就行了。但是我已经研究过了,它看起来只告诉Python它是一个模块,但是它不足以允许我所寻找的这种导入,就像在其他任何库中一样。在

因此,我尝试(当前未在bitbucket中更新)将其用作__init__.py

__title__ = 'pygpstools'
__version__ = '0.1.1'
__author__ = 'Roman Rodriguez'
__license__ = 'MIT'
__copyright__ = 'Copyright 2013 Roman Rodriguez'


import almanacs
import constants
import geodesy
import gpstime
import satellite

但是仍然不起作用:ImportError对于GPSTime。在

我错过了什么?在


Tags: 模块文件方法pyimportinitromanconstants
1条回答
网友
1楼 · 发布于 2024-09-30 03:24:22

例如,GPSTime在模块gpstime中,因此它的实际(相对)名称是gpstime.GPSTime。因此,当您在__init__中导入gpstime时,实际上是在使用名称gpstime,该名称包含对您的类型的引用gpstime.GPSTime。在

所以您必须使用from pygpstools import gpstime,然后使用gpstime.GPSTime作为类型名。在

显然这不是您想要的,因此您需要“收集”您在__init__模块中的所有类型。您可以通过直接提供它们来实现:

from almanacs import *
from constants import *
from geodesy import *
from gpstime import GPSTime
from satellite import * 

我现在使用*导入任何内容,因为我没有仔细查看文件中的实际类型。但您应该指定它。还建议在您的__init__中定义一个__all__列表,以便您可以控制写入from pygpstools import *时导入哪些名称。在

相关问题 更多 >

    热门问题