Article directory:
- __call__
- __iter__
- Yeild
- Arrage
__call__ Callable Object
#!/usr/bin/env python#!-*-coding:utf-8-*-" "switch (c+) @author xyt callable Object" "classG_DPM (object):def __init__(self,g): SELF.G=gdef __call__(self,t):returnSelf.g*t**2E_DPG=G_DPM (9.8) s=E_DPG (2)#free fall distance after 2 seconds.
Dynamic functions:
Use eval to convert to function name (expression), then call function
classStudent (object):def中文版 (self):Print "hello!" defChina (self):Print "Hi there! " def __call__(self,*args): eval (args[0]) self.english () Stu=student () 中文版='中文版'Stu (中文版)
__iter__ use of Iterative objects:
#!/usr/bin/env python#!-*-coding:utf-8-*-" "introducing Python's built-in function, ITER, and the two functions in the class __iter__,__next__iter function have two usages, one is to pass a parameter, and the other is to pass two parameters. The returned result is the return of a iterator object. First of all, say two parameters, such as Python code collection Code I1 = ITER (ITR, ' C ') This means that return to ITR iterator, and in the subsequent iterations, the iteration out of ' C ' immediately stop. What are the requirements for this ITR? This ITR must be callable here, that is, to implement the __CALL__ function" "classItr (object):def __init__(self): Self.result=[1,2,3,4,5,6,7,8,9] SELF.I=iter (Self.result)def __call__(self): res=Next (SELF.I)Print("__call__ called, which would return", Res)returnResdef __iter__(self):returniter (self.result) ITR=Itr () a=iter (ITR) forIinchA:PrintI a=iter (itr,4) forIinchA:PrintI
Yeild
The function with yield is called generator (generator) in Python
def Fab (max): Print Max = 0, 0, 1 while n < Max: yield b = b, A + b = n + 1 a=fab (one) for in A: Print i
Simply put, the function of yield is to turn a function into a generator, the function with yield is no longer a normal function, the Python interpreter treats it as a generator, and the Call to FAB (5) does not execute the FAB function, but instead returns a Iterab Le Object! When the For loop executes, each loop executes the code inside the FAB function, and when it executes to yield B, the FAB function returns an iteration value, and the next iteration, the code proceeds from the next statement of Yield B, and the local variable of the function looks exactly the same as before the last break, so the function Continue execution until yield is encountered again.
Xrange iterating through Iterable objects
For I in range (+): Pass
Causes a List of 1000 elements to be generated, and the code:
For I in Xrange (£): Pass
A List of 1000 elements is not generated, but the next value is returned in each iteration, and the memory footprint is small. Because Xrange does not return a List, it returns a Iterable object.
Technical details of Python development (iii) Advanced syntax