为什么使用 apt.Cache 而不是 apt.cache.Cache() 创建对象

Why object is created using apt.Cache rather than apt.cache.Cache()

我卡在了一个点上,我无法进步,很抱歉这个愚蠢的问题。我为此进行了很多搜索,但我不知道我错过了什么。请帮助我。

我在 python 中学习了模块和 classes。现在我想使用 python 和 apt 进行一些操作。我正在学习:http://apt.alioth.debian.org/python-apt-doc/library/apt.cache.html 但是,我无法理解,模块是apt.cache,如页面顶部所示。我预计应该通过编写 apt.cache.Cache() 创建对象,但是通过编写 apt.Cache() 创建对象,如下所示。为什么?

    import apt
    import apt.progress

    # First of all, open the cache
    cache = apt.Cache()
    # Now, lets update the package list
    cache.update()
    # We need to re-open the cache because it needs to read the package list
    cache.open(None)
    # Now we can do the same as 'apt-get upgrade' does
    cache.upgrade()
    # or we can play 'apt-get dist-upgrade'
    cache.upgrade(True)
    # Q: Why does nothing happen?
    # A: You forgot to call commit()!
    cache.commit(apt.progress.TextFetchProgress(),
                 apt.progress.InstallProgress())

第二个类似的问题是关于下面的代码,缓存 class 是从模块 apt.cache 导入的。我预计该对象将通过编写 apt.cache.Cache() 创建,但它是通过编写 apt.Cache() 创建的。为什么?

    >>> from apt.cache import FilteredCache, Cache, MarkedChangesFilter
    >>> cache = apt.Cache()
    >>> changed = apt.FilteredCache(cache)
    >>> changed.set_filter(MarkedChangesFilter())
    >>> print len(changed) == len(cache.get_changes()) # Both need to have same length
    True

提前致谢

如果您查看 apt package__init__.py 文件,您会看到以下行:

__all__ = ['Cache', 'Cdrom', 'Package']

python documentation 说:

The import statement uses the following convention: if a package’s __ init__.py code defines a list named all, it is taken to be the list of module names that should be imported when from package import * is encountered.

这就是您可以使用 apt.Cache()

的原因

对于问题的第二部分,您可以使用

直接导入缓存 class
from apt.cache import Cache
cache = Cache()

您还可以使用

导入缓存class
import apt
cache = apt.Cache()       //because of the __all__ variable in __init__.py
cache = apt.cache.Cache() //because it's a fully qualified name