Python generator objects: __sizeof__()

前端 未结 5 464
醉话见心
醉话见心 2020-12-09 10:37

This may be a stupid question but I will ask it anyway. I have a generator object:

>>> def gen():
...     for i in range(10):
...         yield i
..         


        
5条回答
  •  情书的邮戳
    2020-12-09 11:08

    As said in other answers, __sizeof__ returns a different thing.

    Only some iterators have methods that return the number of not returned elements. For example listiterator has a corresponding __length_hint__ method:

    >>> L = [1,2,3,4,5]
    >>> it = iter(L)
    >>> it
    
    >>> it.__length_hint__()
    5
    >>> help(it.__length_hint__)
    Help on built-in function __length_hint__:
    
    __length_hint__(...)
        Private method returning an estimate of len(list(it)).
    
    >>> it.next()
    1
    >>> it.__length_hint__()
    4
    

提交回复
热议问题