有没有一种方法可以在Python 3中将生成器子类化? [英] Is there a way to subclass a generator in Python 3?

查看:60
本文介绍了有没有一种方法可以在Python 3中将生成器子类化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了显而易见的以外,我还想尝试一下,以防万一:

Aside from the obvious, I thought I'd try this, just in case:

def somegen(input=None):
    ...
    yield
    ...

gentype = type(somegen())
class subgen(gentype):
    def best_function_ever():
        ...

A,Python的反应非常敌对:

Alas, Python's response was quite hostile:

"TypeError: Type generator is not an acceptable base type"

很幸运,这对我来说是个问题.瞧,我在想,如果有机会的话,也许会成为一种有趣的基本类型.想象一下我的惊喜!..和沮丧.有没有办法让全能的Python在这本书上以我的方式看待事物?

As luck would have it, that's a problem for me. See, I was thinking that maybe it would be a fun base type to play with, if I gave it a chance. Imagine my surprise! ..and dismay. Is there no way to get the almighty Python to see things my way on this one?

这无疑是一个开箱即用的问题,所以请不要只是说如果您无法立即想到一种方法,那是不可能的.Python(尤其是Py3)非常灵活.

This is most certainly an outside-the-box kinda question, so please don't just say that it's not possible if you can't think of a way immediately. Python (especially Py3) is very flexible.

当然,如果您有证据证明为什么不能(不是不应该")成为基本类型(Py3),那么我要做就想明白这一点.

Of course, if you have evidence of why it cannot (not "should not") be a base type (Py3), then I do want to see and understand that.

推荐答案

您不能使用 yield 将生成器定义为函数,但是可以在其他生成器中使用它.

You cannot subclass a generator that is defined as a function using yield, but you can use it in another generator.

就拿这个简单的一个吧:

Just take this simple one :

def alphagen(n=27):
    if n<0 or n > 27: n = 27
    for i in range(n):
        yield chr(ord('A') + i)

您得到了:

>>>> [ a for a in alphagen(10)]
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']

您可以在以下位置使用它:

You can use it in:

def alphastartgen(n=27):
    resul = ""
    for i in alphagen(n):
        resul += i
        yield resul

现在您得到了:

>>> [ a for a in alphastartgen(8) ]
['A', 'AB', 'ABC', 'ABCD', 'ABCDE', 'ABCDEF', 'ABCDEFG', 'ABCDEFGH']

这篇关于有没有一种方法可以在Python 3中将生成器子类化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆