python - 在 python 中子类化内置枚举

标签 python built-in enumerate

考虑下面的代码。我正在尝试对内置 enumerate 进行子类化,以便它为 for 循环的每一轮打印一行。代码似乎可以正常工作,这令人惊讶,因为我从未调用过 super().__init__(x)。那么,这里发生了什么?谁以正确的方式初始化基类 enumerate?这里发生的 __new__ 方法有什么魔力吗?

class myenum(enumerate):
    def __init__(self,x):
        self.x_   = x
        self.len_ = len(x)
        
    def __next__(self):
        out = super().__next__()
        print(f'Doing {out[0]} of {self.len_}')
        return out

for ictr, key in myenum(['a','b','c','d','e']):
    print('Working...')

最佳答案

__init__方法总是可选的。实例的所有初始化始终可以完全在 __new__ 中完成方法,enumerate 就是这种情况类,其__new__方法定义hereenum_new_impl函数,您可以在其中看到 iterable参数存储为属性 en_sit返回对象的 en , 结构类型 enumobject :

static PyObject *
enum_new_impl(PyTypeObject *type, PyObject *iterable, PyObject *start)
{
    enumobject *en;

    ...

    en->en_sit = PyObject_GetIter(iterable);

    ...

    return (PyObject *)en;
}

关于python - 在 python 中子类化内置枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74806815/

相关文章:

python - Azure 函数 - func 开始给出值不能为空的错误。参数名称: provider

android - Android Automotive 与 Google 内置的区别

windows - 为 OpenGL 渲染枚举设备和显示模式

ios - 如何获取按索引配对的两个单独的 Int 数组的值,然后对某些对进行条件运算?

bash - 不要在多个 bash 脚本中显示 pushd/popd 堆栈(安静的 pushd/popd)

python - 在 python 中枚举到 For 循环

python - 如何以编程方式检查 Kafka Broker 是否已启动并在 Python 中运行

python - Scipy LDL 分解返回意外结果

python - 从用 Swift 编写的现有项目中调用 Python 代码

c++ - __builtin_clz() 为负