相关疑难解决方法(0)

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

为了转换到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')
Run Code Online (Sandbox Code Playgroud)

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

python python-2.7

15
推荐指数
1
解决办法
6511
查看次数

标签 统计

python ×1

python-2.7 ×1