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

梅蒂斯

我被困在一个点上,我无法前进,对这个愚蠢的问题感到抱歉。我为此进行了很多搜索,但我不知道自己缺少什么。请帮我。

我研究了python中的模块和类。现在,我想使用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())

第二个类似的问题是关于以下代码,Cache类是从模块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

提前致谢

Ortomala Lokni

如果查看__init__.pyapt软件包文件,则会看到以下行:

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

python文档说:

import语句使用以下约定:如果程序包的__ init__.py代码定义了一个名为all的列表,则将其视为遇到从包import *时应导入的模块名称的列表。

这就是为什么您可以使用的原因 apt.Cache()

对于问题的第二部分,您可以使用以下命令直接导入Cache类:

from apt.cache import Cache
cache = Cache()

您也可以使用以下命令导入Cache类:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章