Learning notes -- iteration 1 of classes in Python

Judge whether it is OK iteration

1. In python, traversing lists, tuples, dictionaries, etc. through the for loop is Iteration

Example 1: traversal list

num = [11, 22, 33, 44, 55]

for x in num:
	print(x)

The results are:
11
22
33
44
55

Example 2: traversal string

 for x in 'abcdef':
     print(x)

a
b
c
d
e
f

But some types cannot be iterated or traversed, such as int shaping

Example 3: Test traversal int

>>> for x in 100:
...     print(x)
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

TypeError: 'int' object is not iterative

2. Which can be iterated?

Tuples, lists, dictionaries, sets, and strings can be iterated, that is to say, as long as the objects can be iterated, they can be iterated

3. How can we judge whether an object can be iterated?

It can be judged by isinstance, a subclass of Iterable in the collection module,
Example 4: judge whether the list can be iterated

>>> from collections import Iterable
>>> isinstance([1, 2, 3],Iterable)
True
>>> isinstance(123,Iterable)
False

isinstance output True indicates that it can iterate, output False indicates that it cannot

4. Can classes / objects iterate?

Sure!

Example 5:

from collections.abc import Iterable


class ClassIterable(object):

    def __init__(self):
        self.contains = list( )

    def addList(self, item):
        self.contains.append(item)

    def __iter__(self):
        pass

classIterable = ClassIterable( )
print('ClassIterable Whether it is an iterative object', isinstance(classIterable, Iterable))

for temp in ClassIterable:
    print(temp)
    
//Printout:
ClassIterable Whether it is an iterative object True
Traceback (most recent call last):
  File ".\1 Iterative object.py", line 18, in <module>
    for temp in classIterable:
TypeError: iter() returned non-iterator of type 'NoneType'

Through the above program, we can find that the classIterable object can be iterated, and the output result is True, but then an error is reported. The error is in 18 lines, that is, when traversing the object with for, the result judged by isinstance can be iterated. Why does this happen? If an object wants to iterate, it must have an
In general, objects can't be iterated directly. How to judge or say that objects can be iterated? In the classiterable object in example 5, there is a "iter" method, which does nothing now. isinstance judges that the reason that classiterable can be traversed is because of it.

To determine whether an object can be iterated is to determine whether there is an "iter" method in the object
  • __The iter method must have a return value, and the return value must be a function containing the "next" method. for traversal is to call the "next" method in the return value of the "iter method"
  • __What is returned by next? What is retrieved by traversal
  • Example 6:
class ClassA(object):

    def __init__(self):
        self.contains = list( )

    def addList(self, item):
        self.contains.append(item)
#If you want an object to be an object that can be iterated, i.e. you can use for, you must use the "iter" method
    def __iter__(self):
        return ClassB()

class ClassB(object):
    def __next__(self):
        return  1
        
classIterable = ClassA( )
for temp in classIterable:
    print(temp)
Implementation object iter ation means that there is a return value in the object, and there is a return value in the return value object

Example 7: iterate over the contents of the object list

class ClassA(object):

    def __init__(self):
        self.contains = list( )

    def addList(self, item):
        self.contains.append(item)
#If you want an object to be an object that can be iterated, i.e. you can use for, you must use the "iter" method
    def __iter__(self):
        return ClassB(self)

class ClassB(object):

    def __init__(self, contain):
        self.contain = contain
    def __next__(self):
        return  self.contain.contains[0]

classIterable = ClassA( )

classIterable.addList('Item 1')
classIterable.addList('Item 2')
classIterable.addList('Item 3')
for temp in classIterable:
    print(temp)
    time.sleep(1)

//Print results:
//Goods1

At this time, the item 1 in the list () will be taken all the time, and the printing cycle will be continued

Technological process
for start - >
1. Judge whether the instance object classIterable created by ClassA can be iterated 1
2. Call the iter function to get the return value of the "iter" method in ClassA
3. The return value of the iterator method is an iterator. Determine whether it is an iterator 2
4. Whether there is a "next" method in the return object of the "iter" method
5. The return value of the next method is the property to be traversed in the traversal object

  1. Judgment method:
    : Print ('classiteratable or not: ', isinstance (classiteratable, iteratable)) ↩︎

  2. Judgement method
    :classIterator = iter(classIterable)
    : print('classIterator is iterator: ', isinstance(classIterator, Iterator)) ↩︎

Published 1 original article · praised 0 · visited 2
Private letter follow

Tags: Python

Posted on Thu, 13 Feb 2020 05:41:48 -0800 by pckidcomplainer