Iteration
An iteration is one repeated pass through a process, and the result of each pass becomes the starting point for the next one. A common example is looping through the elements of a container.
Any object that implements __iter__ can return an iterator object.
1 2 3 4 5 6 7</th>
<th># 创建: class 可迭代对象名称: def __iter__(self): return 迭代器 # 使用: for 变量名 in 可迭代对象: 语句</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>
What a for loop does internally is essentially this:
1 2 3 4 5 6</th>
<th>迭代器 = 可迭代对象.__iter__() # 实例一个迭代器对象。 while True: try: print(迭代器.__next__()) # 调用迭代器中的`__next__`方法。 except StopIteration: # 在迭代器 raise StopIteration 后停止。 break</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>
An iterator is an object that can be called with __next__() to produce the next value.
1 2 3 4 5 6 7 8</th>
<th>class 迭代器类名: def __init__(self, 聚合对象): # 聚合对象通常是容器对象。 self.聚合对象= 聚合对象 def __next__(self): if 没有元素: raise StopIteration return 聚合对象元素</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>
The benefit of iterators is that they provide a single, clean way to access elements from an aggregate object without needing to care about its internal structure.
Generators
A generator is an iterable that provides data dynamically: each loop computes one value and returns one value. Instead of building a full container to store all results up front, it derives data during iteration according to a rule or algorithm, which saves memory.
The larger the dataset, the more obvious this advantage becomes. This behavior is also called lazy evaluation or deferred evaluation: results are computed only when needed rather than being produced all at once.
Any function containing a yield statement is a generator function. Calling that function returns a generator object, but the function body does not run immediately.
1 2 3 4 5 6 7 8 9</th>
<th># 创建: def 函数名(): 代码 yield 数据 代码 # 调用: for 变量名 in 函数名(): 语句</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Calling a generator function automatically creates an iterator object. The generator function starts executing only when __next__() is called on that iterator. Each time execution reaches yield, it returns a value and pauses temporarily. On the next __next__() call, execution resumes exactly where it left off.
When possible, generators are usually the preferred choice.
Python also provides several built-in generator-style tools:
range: creates a counting generator object.enumerate: when iterating over an iterable, it pairs each item with its index as a tuple.zip: combines corresponding elements from multiple iterables into tuples; the total number of tuples is determined by the shortest iterable.- Generator expressions: create generator objects using comprehension syntax.
变量 = (表达式 for 变量 in 可迭代对象 if 条件) reduce: performs cumulative processing over a parameter sequence. In Python 3.x,reduce()was moved into thefunctoolspackage.
Functional Programming
In Python, one of the foundations of functional programming is that functions can be assigned to variables and invoked indirectly. That makes function usage more flexible.
Functional programming becomes especially useful when multiple functions share the same overall structure, but differ in their core algorithm or condition. The varying part can be separated out. From an object-oriented perspective, this pattern can be understood like this:
- Encapsulation: package the varying behavior into separate functions, then pass those functions in as data so they can be called inside another function.
- Inheritance: isolate the changing part of the current function through function-type parameters.
- Polymorphism: call the function-type parameter while coding, but at runtime the actual function argument determines the behavior.
Passing the core logic or changing behavior into a method makes that method more broadly applicable, which reflects the open-closed principle in object-oriented design.
The mindset behind building these variation points is functional programming itself: avoid side effects, do not change or depend on data outside the current function, and make functions self-descriptive so the code is easier to read.
Lambda Expressions
A lambda expression is an anonymous function. It provides a concise way to define small functions, especially when passing a function as an argument. The syntax is compact and elegant, and often improves readability. Because lambda functions can be created and discarded on the spot, they also help reduce coupling.
<table> <thead> <tr> <th>1 2 3 4 5 6</th>
<th># 定义: 变量 = lambda 形参: 方法体 # 注意:代码规范PEP8不推荐使用这种方法 def # 调用: 变量(实参)</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>
If there are no parameters, the parameter list can be omitted. The body can contain only a single expression, and assignment statements are not supported.
Common built-in higher-order functions include:
map(函数, 可迭代对象): applies the function to each element of the iterable and returns a new iterable made from the returned values.filter(函数, 可迭代对象): filters elements from the iterable according to a condition and returns a new iterable.sorted(可迭代对象, key = 函数,reverse = bool值): sorts data and returns the sorted result.max(可迭代对象, key = 函数): returns the maximum item according to the function.min(可迭代对象, key = 函数): returns the minimum item according to the function.
Decorators and Nested Functions
A nested function is formed by a function together with the reference environment associated with it.
Because the logic remains continuous, calling the inner function does not break away from the current logical context. The tradeoff is that external variables remain in memory and are not released after the call ends, which can occupy memory.
An inner function can access variables from the outer function, and the outer function can return the inner function.
<table> <thead> <tr> <th>1 2 3 4 5 6 7 8 9 10</th>
<th># 定义: def 外部函数名(参数): 外部变量 def 内部函数名(参数): 使用外部变量 return 内部函数名 # 调用: 变量 = 外部函数名(参数) 变量(参数)</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Python decorators are built on this idea of nested functions.
A decorator is a function that adds new behavior to an existing function without changing how that function is called or altering its internal code.
<table> <thead> <tr> <th>1 2 3 4 5 6 7 8 9 10 11</th>
<th>def 函数装饰器名称(func): def wrapper(*args, **kwargs): 需要添加的新功能 return func(*args, **kwargs) return wrapper @ 函数装饰器名称 def 原函数名称(参数): 函数体 原函数(参数)</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Using @函数装饰器名称 above a function is equivalent to creating a variable with the same name as the original function and binding it to the inner function returned by the decorator. In other words, calling the original function name actually executes the wrapper function. The relationship is:
原函数名称 = 函数装饰器名称(原函数名称)
A single function can be wrapped by multiple decorators. They execute from the nearest one outward, which is known as a decorator chain.