gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:53:24 33 4
gpt4 key购买 nike

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

我研究了 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())

第二个类似的问题是关于下面的代码,缓存类是从模块 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 的 __init__.py 文件 package ,你会看到这一行:

__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()

的原因

对于问题的第二部分,您可以直接导入 Cache 类

from apt.cache import 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

关于python - 为什么使用 apt.Cache 而不是 apt.cache.Cache() 创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28933807/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com