Modules
A Python program can be split into modules, which are files ending in .py. This is a practical way to separate similar logic and keep related code together.
Once code is divided across files, the structure becomes easier to read and maintain, and collaboration also becomes smoother. To connect one file with another, members from a target module are imported into the current module’s scope.
<table> <thead> <tr> <th>1 2 3 4 5</th>
<th># 你过来,面向过程比较多,因为用的是文件名。 import 模块 as 名称 # 主动过来,面向对象,直接可以拿来用。 from 模块 import 成员1, 成员1, 成员1</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>
If names conflict, Python follows the nearest-scope rule. Even so, it is best to avoid naming collisions whenever possible.
Common naming conventions in layered projects include:
- BLL: business logic layer
- DAL: data access layer
- USL: user show layer
- model: model layer
- main: program entry point
The special variable __name__ shows the name of the current module. When its value is __main__, that means the file is being run as the main module—the first module executed, not one being imported by another file.
Python is an interpreted language, but to improve startup speed and execution efficiency, it also uses a compiled form internally. After compilation, Python produces .pyc files inside __pycache__, which store bytecode, a Python-specific intermediate representation.
if __name__ == '__main__' is used to ensure that certain code only runs when the current file is started directly.
One important detail about imports: when a module is imported, all of its statements are executed. If that module has already been imported once, importing it again will not re-run those statements.
Packages
A package is a way to organize modules using folders. It groups related modules together so the overall logic of a project is clearer.
<table> <thead> <tr> <th>1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16</th>
<th># 语法 import 包 # 将包中__init__模块内整体导入到当前模块中 import 包 as 别名 # 使用 包.成员 别名.成员 # 语法 from 包 import 成员 # 将包中__init__模块内的成员导入到当前模块作用域中 from 包 import 成员 as 别名 from 包 import * # 小心重名问题 # 使用 成员 别名</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Using packages helps keep a project from turning into a pile of unrelated files. When modules are grouped by responsibility, the codebase is easier to navigate and reason about.
Exception Handling
An exception is an error detected at runtime. Once an exception occurs, the program stops continuing normally and control jumps back to the point where the function was called.
Some common exceptions are:
NameError: a variable has not been defined.TypeError: an operation is performed on incompatible data types.IndexError: an index is out of range.AttributeError: an object does not have the requested attribute.KeyError: a key does not exist.Exception: the base class for exceptions.
The raise statement is used to throw an error manually and force the program into an exceptional state. This is especially useful when the call stack is deep. Passing error information upward through repeated return values can be awkward, while raising an exception sends that information directly to the caller.
To turn an exceptional state back into a controlled flow, Python provides structured exception handling:
<table> <thead> <tr> <th>1 2 3 4 5 6 7 8 9 10 11 12</th>
<th>try: 可能触发异常的语句 except 错误类型1 [as 变量1]: 处理语句1 except 错误类型2 [as 变量2]: 处理语句2 except Exception [as 变量3]: 不是以上任何错误类型的处理语句 else: 未发生异常的语句 finally: 无论是否发生异常的语句</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>
A few rules are worth keeping in mind:
- The
asclause binds the exception object to a variable, and it can be omitted. - There can be one or more
exceptclauses, each used to catch a particular type of error. - There can be at most one
elseclause. - There can be at most one
finallyclause. If there is noexceptclause, thenfinallymust be present. - If an exception is not caught, it continues propagating upward to the caller until the program eventually terminates.
In practice, exceptions are not only for handling mistakes—they are also a way to pass failure information through different layers of a program in a clean and direct way.