notes on python

iterator

Behind the scenes, the for statement calls iter() on the container object. The function returns an iterator object that defines the method __next__() which accesses elements in the container one at a time. When there are no more elements, __next__() raises a StopIteration exception which tells the for loop to terminate.You can call the __next__() method using the next() built-in function html

能夠本身實現一個類的for loop: python

class A:
	class it:
		def __init__(s,a):
			s.a=a
			s.l=len(s.a.l)+len(s.a.l2)
			s.i=0
		def __next__(s):
			if s.i==s.l:
				raise StopIteration
			a=0
			if s.i<len(s.a.l):
				a= s.a.l[s.i]
			else:
				a= s.a.l2[s.i-len(s.a.l)]
			s.i=s.i+1
			return a
	def __init__(s):
		s.l=[1,2,4,5]
		s.l2=[4,3,2,0]
	def __iter__(s):
		return A.it(s)

>>> a=A()
>>> [i for i in a]
[1, 2, 4, 5, 4, 3, 2, 0]

generator

Generators are a simple and powerful tool for creating iterators. They are written like regular functions but use the yield statement whenever they want to return data. Each time next() is called on it, the generator resumes where it left off (it remembers all the data values and which statement was last executed). express

def gen(a):
	for i in a.l:
		yield i
	for i in a.l2:
		yield i

>>>for i in gen(a):
	print (i,end=',')

1,2,4,5,4,3,2,0,

generator expression

def gen():
	return ((i,j)for i in range(10)for j in range(9))
或:
for a in((i,j)for i in range(10)for j in range(9)):
	print (a)

for a in (...generator exp...)是在每次call next()時才生成a,而for a in [...list comprehension...]是提早就生成一個列表,聽說前者效率更高 app

class and instance variables

個人理解,對於mutable變量,對象複製類的變量的一個「指針「: 函數

>>> class A:
	li=[]
	def add(s,x):
		s.li.append(x)

		
>>> a=A()
>>> a.add(3)
>>> a.li
[3]
>>> b=A()
>>> b.add(4)
>>> b.li#b.li像是A.li的一個引用,已經被a.li修改過
[3, 4]
正確的作法:
>>> class A:
	def __init__(s):
		s.li=[]#每次建立對象都生成一個對象本身的列表
	def add(s,x):
		s.li.append(x)

		
>>> a=A()
>>> a.add(3)
>>> a.li
[3]
>>> b=A()
>>> b.add(4)
>>> b.li
[4]

而對於immutable 變量則相似於按值傳遞(儘管python中沒有這些概念),不會有這個問題 oop

函數嵌套

>>> def fun_gen(c):
...     def fun(x):
...             return x+c
...     return fun
... 
>>> f=fun_gen(4)
>>> f(5)
9
>>> fun_gen(5)(8)
13
相關文章
相關標籤/搜索