繁体   English   中英

Python-如何从扩展名称空间导入父包

[英]Python - How do I import parent package from extended namespace

所以我有两个不同的包裹。 第一个是我的主软件包“ bobzilla”,另一个软件包扩展了第一个“ bobzilla.structure”。

bobzilla/
  __init__.py

其中bobzilla / __ init__.py包含:

class Foo(object):
    def __init__(self, bar):
        self.bar=bar

和:

bobzilla/
  __init__.py
  structure/
    __init__.py

其中bobzilla / structure / __ init__.py包含:

import bobzilla
foo=Foo("bar")

当执行bobzilla / structure / __ init__.py时,我得到:

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

我的问题是,如何从“ bobzilla.structure”引用命名空间“ bobzilla”,而不会覆盖“ bobzilla.structure”。

注意:

设置“此问题可能已经在这里有了答案”的人是错误的。 我已经尝试过了,但是没有用。 这是两个不同的程序包,而不是相同的程序包。

似乎您在尝试创建名称空间包而不创建名称空间包,这将无法正常工作。

要明确指定一个包作为一个命名空间包,您需要使用pkgutil库(或票友东东setuptools ),像这样在顶部bobzilla/__init__.py

__path__ = pkgutil.extend_path(__path__, __name__)

如果需要隐式命名空间包 ,则可以在Python 3.3和更高版本中执行此操作……但bobzillabobzilla 隐式名称空间包不能包含__init__.py文件,并且除了其模块外,将永远没有任何内容。 (好吧,您可以创建一个隐式名称空间包,然后添加一个子包或外部模块,以在创建后将其显式添加到其中……但是我不确定为什么要这么做。)

bobzilla/structure/__init__.py应该是:

from bobzilla import Foo
foo=Foo("bar")

用问题中提到的相同结构和代码测试以上内容。 bobzilla/path/to/test 结果:

>>> from site import addsitedir
>>> addsitedir("/path/to/test")
>>> import bobzilla.structure as struc
>>> struc.foo
<bobzilla.Foo object at 0x7f2f8c716810>
>>> 

尝试:

import bozilla.structure as struct
import bozilla

NLTKhttp://nltk.org的工作示例:

>>> import nltk.corpus as corpus
>>> nltk
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'nltk' is not defined
>>> import nltk
>>> nltk.corpus
<LazyModule 'nltk.corpus'>
>>> corpus
<LazyModule 'nltk.corpus'>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM