# Get all the methods of an object :dir()
s = 'hello world'
l = [1, 2, 3]
print(dir(s))
print(dir(l))
# Iteratable object : The interior contains __iter__ Object of method
# Iteratible objects cannot pass directly through for The loop takes values directly
# Now we can directly do... On the iteratable object for Value cycle , because for Internal transformation has been made , First convert the iteratable object into an iterator , Reuse next Take the value
print('__iter__' in dir(s))
# iterator : The interior contains __iter__ Method and contains __next__ Object of method ( File handle )
# advantage : Save memory 、next once , Take only one value .
with open('test', encoding='utf-8', mode='w') as f:
pass
print('__iter__' in dir(f) and '__next__' in dir(f)) # True
# Iteratable objects can be converted to iterators
strs = 'hello world'
ret1 = iter(strs)
ret2 = strs.__iter__()
print(ret1, ret2)
# Value iterator : next() Methods or .__next__() Method , once next() Take a value
res = iter(strs)
print(next(res)) # h
print(res.__next__()) # e
l1 = [11, 33, 44, 55, 66, 77]
# List to iterator
ret = iter(l1)
print(ret)
for i in range(len(l1)):
print(next(ret))
# utilize while Loop simulation for The mechanism of loop fetching iteratable objects .( interview )
ss = 'asdfghjkl'
obj = iter(ss) # Convert an iteratable object to an iterator
while True:
try:
print(next(obj))
except StopIteration:
break