繁体   English   中英

在python中,为什么要从内置模块导入'object'?

[英]In python, why import 'object' from builtins module?

为了转换到python 3,我试图理解编写python 2和python 3兼容代码。 以下代码来自python-future.org并说明了构造一个与两个版本的python兼容的迭代器的方法。

from builtins import object

class Upper(object):
    def __init__(self, iterable):
        self._iter = iter(iterable)
    def __next__(self):      # Py3-style iterator interface
        return next(self._iter).upper()  # builtin next() function calls
    def __iter__(self):
        return self

itr = Upper('hello')
assert next(itr) == 'H'      # compatible style
assert list(itr) == list('ELLO')

代码在python 2中运行良好,但令我惊讶的是,如果我删除import语句然后我得到一个错误TypeError: Upper object is not an iterator 我经常从object派生我的自定义类,但我从未从内置导入它。 为什么简单地导入object改变代码的行为?

您( future.builtins )从future.builtins模块导入; 它提供了一个自定义 object基类,可以添加前向特殊名称。

在Python 2中,迭代器必须有next()方法 (以及__iter__ ); 这个方法在Python 3中被重命名为__next__ 通过不使用future.builtins.object版本,您只是缺少Python 2中提供的next - > __next__别名。

请参阅future.types.newobject.py源代码

 def next(self): if hasattr(self, '__next__'): return type(self).__next__(self) raise TypeError('newobject is not an iterator') 

请注意,如果您运行的是Python 3,则builtins将返回标准的内置对象,该模块仅为Python 2返回类似这些的填充程序。

您可以自己添加相同的别名:

class Upper(object):
    def __init__(self, iterable):
        self._iter = iter(iterable)

    def __iter__(self):
        return self

    def __next__(self):      # Py3-style iterator interface
        return next(self._iter).upper()  # builtin next() function calls
    next = __next__          # Py2 alias

暂无
暂无

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

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