# 变量和标识符
# 变量
变量是用于存储数据的容器,变量名可以包含字母、数字和下划线,但不能以数字开头。
| a = 1 |
| b = 2 |
| c = a + b |
| print(c) |
# 标识符
标识符是用于标识变量、函数、类、模块等的名称。标识符的命名规则如下:
- 标识符可以包含字母、数字和下划线,但不能以数字开头。
- 标识符不能包含空格和特殊字符。
- 标识符区分大小写。
- 标识符不能是 Python 的关键字。
| |
| my_variable = 10 |
| my_variable_2 = 20 |
| my_variable3 = 30 |
| |
| |
| |
| |
| |
| |
| |
# 数据类型
# 整数 (int)
整数是用于表示整数的类型,例如 1、2、3 等。
# 浮点数 (float)
浮点数是用于表示小数的类型,例如 1.0、2.5、3.14 等。
# 字符串 (str)
字符串是用于表示文本的类型,例如 "hello"、"world" 等。
| string1 = "hello" |
| string2 = 'world' |
字符串常见操作:
- 字符串拼接:使用
+
运算符将两个字符串连接起来。
- 字符串重复:使用
*
运算符将字符串重复指定次数。
- 字符串长度:使用
len()
函数获取字符串的长度。
| a = "hello" |
| print(len(a)) |
- 字符串切片:使用
[:]
运算符获取字符串的子串。
- 字符串查找:使用
find()
函数查找子串在字符串中的位置。
| a = "hello" |
| print(a.find("l")) |
- 字符串替换:使用
replace()
函数替换字符串中的子串。
| a = "hello" |
| print(a.replace("l", "x")) |
- 字符串分割:使用
split()
函数将字符串分割成子串列表。
| a = "hello world" |
| print(a.split(" ")) |
- 字符串大小写转换:使用
upper()
、 lower()
、 capitalize()
、 title()
函数进行大小写转换。
upper()
:将字符串转换为大写。
lower()
:将字符串转换为小写。
capitalize()
:将字符串的首字母转换为大写。
title()
:将字符串的每个单词的首字母转换为大写。
| a = "hello" |
| print(a.upper()) |
| print(a.lower()) |
| print(a.capitalize()) |
| print(a.title()) |
- 字符串格式化:使用
%
运算符或 format()
函数进行字符串格式化。
%
运算符:使用 %
运算符进行字符串格式化,格式化字符串中的 %s
、 %d
等占位符会被后面的参数替换。
format()
函数:使用 format()
函数进行字符串格式化,格式化字符串中的 {}
占位符会被后面的参数替换。
| name = "Alice" |
| age = 25 |
| print("My name is %s and I am %d years old." % (name, age)) |
| print("My name is {} and I am {} years old.".format(name, age)) |
- 字符串拼接:使用
join()
函数将列表中的字符串拼接成一个字符串。
| a = ["hello", "world"] |
| print(" ".join(a)) |
- 字符串判断:使用
startswith()
、 endswith()
、 isalpha()
、 isdigit()
、 isalnum()
、 isspace()
函数判断字符串的属性。
startswith()
:判断字符串是否以指定子串开头。
endswith()
:判断字符串是否以指定子串结尾。
isalpha()
:判断字符串是否只包含字母。
isdigit()
:判断字符串是否只包含数字。
isalnum()
:判断字符串是否只包含字母和数字。
isspace()
:判断字符串是否只包含空白字符。
| a = "hello" |
| print(a.startswith("h")) |
| print(a.endswith("o")) |
| print(a.isalpha()) |
| print(a.isdigit()) |
| print(a.isalnum()) |
| print(a.isspace()) |
# 列表 (list)
列表是用于存储多个元素的有序集合,可以包含不同类型的元素。
| a = [1, 2, 3, 4, 5] |
| b = ["hello", "world"] |
| c = [1, "hello", 3.14] |
初始化:
| |
| empty_list = [] |
| empty_list = list() |
| |
| |
| numbers = [1, 2, 3, 4, 5] |
| fruits = ['apple', 'banana', 'orange'] |
| mixed = [1, 'two', 3.0, [4, 5]] |
| |
| |
| squares = [x**2 for x in range(10)] |
| even_numbers = [x for x in range(20) if x % 2 == 0] |
| |
| |
| from_iterable = list('hello') |
| from_range = list(range(5)) |
列表常见操作:
- 访问列表元素:使用索引访问列表中的元素。
| a = [1, 2, 3, 4, 5] |
| print(a[0]) |
| print(a[2]) |
- 修改列表元素:使用索引修改列表中的元素。
| a = [1, 2, 3, 4, 5] |
| a[0] = 10 |
| print(a) |
- 删除列表元素:使用
del
语句删除列表中的元素。
| a = [1, 2, 3, 4, 5] |
| del a[0] |
| print(a) |
- 列表切片:使用
[:]
运算符获取列表的子列表。
| a = [1, 2, 3, 4, 5] |
| print(a[1:3]) |
- 列表长度:使用
len()
函数获取列表的长度。
| a = [1, 2, 3, 4, 5] |
| print(len(a)) |
- 列表追加:使用
append()
方法将元素追加到列表末尾。
| a = [1, 2, 3, 4, 5] |
| a.append(6) |
| print(a) |
- 列表插入:使用
insert()
方法将元素插入到列表指定位置。
| a = [1, 2, 3, 4, 5] |
| a.insert(1, 10) |
| print(a) |
- 列表删除:使用
remove()
方法删除列表中指定值的第一个元素。
| a = [1, 2, 3, 4, 5] |
| a.remove(3) |
| print(a) |
- 列表排序:使用
sort()
方法对列表进行排序。
| a = [5, 3, 1, 4, 2] |
| a.sort() |
| print(a) |
- 列表反转:使用
reverse()
方法将列表中的元素反转。
| a = [1, 2, 3, 4, 5] |
| a.reverse() |
| print(a) |
- 列表合并:使用
+
运算符将两个列表合并成一个列表。
| a = [1, 2, 3] |
| b = [4, 5, 6] |
| c = a + b |
| print(c) |
- 列表复制:使用
copy()
方法复制列表。
| a = [1, 2, 3] |
| b = a.copy() |
| print(b) |
- 查找列表中元素:使用
in
运算符判断元素是否在列表中。
| fruits = ['apple', 'banana', 'orange', 'grape'] |
| |
| |
| print('apple' in fruits) |
| print('watermelon' in fruits) |
| |
| |
| if 'kiwi' not in fruits: |
| print("Kiwi is not in the list") |
| |
| |
| |
| count = fruits.count('banana') |
| print(count > 0) |
- 添加元素的方法
| |
| fruits = ["apple", "banana"] |
| fruits.append("orange") |
| print(fruits) |
| |
| |
| fruits = ["apple", "banana"] |
| fruits.insert(1, "mango") |
| print(fruits) |
| |
| |
| fruits = ["apple", "banana"] |
| fruits.extend(["orange", "grape"]) |
| print(fruits) |
| |
| |
| fruits = ["apple", "banana"] |
| more_fruits = fruits + ["kiwi", "pear"] |
| print(more_fruits) |
| |
| |
| fruits = ["apple", "banana"] |
| fruits += ["kiwi", "pear"] |
| print(fruits) |
| |
| |
| numbers = [1, 2, 3] |
| doubled_numbers = [x * 2 for x in numbers] |
| print(doubled_numbers) |
# 元组 (tuple)
元组是用于存储多个元素的有序集合,与列表类似,但元组是不可变的、有序的集合,用圆括号 () 表示。
| a = (1, 2, 3, 4, 5) |
| b = ("hello", "world") |
| c = (1, "hello", 3.14) |
初始化
| |
| empty_tuple = () |
| empty_tuple = tuple() |
| |
| |
| coordinates = (10, 20) |
| colors = ('red', 'green', 'blue') |
| mixed = (1, 'two', 3.0, [4, 5]) |
| |
| |
| single_element = (42,) |
| not_a_tuple = (42) |
| |
| |
| from_list = tuple([1, 2, 3]) |
| from_string = tuple('abc') |
元组常见操作:
- 访问元组元素:使用索引访问元组中的元素。
| a = (1, 2, 3, 4, 5) |
| print(a[0]) |
| print(a[2]) |
- 列表切片:使用
[:]
运算符获取元组的子元组。
| a = (1, 2, 3, 4, 5) |
| print(a[1:3]) |
- 元组长度:使用
len()
函数获取元组的长度。
| a = (1, 2, 3, 4, 5) |
| print(len(a)) |
- 元组解包:使用
=
运算符将元组中的元素赋值给多个变量。
| a = (1, 2, 3) |
| x, y, z = a |
| print(x) |
| print(y) |
| print(z) |
- 查找元组中元素:使用
in
运算符判断元素是否在元组中。
| |
| colors = ('red', 'green', 'blue', 'yellow') |
| |
| print('red' in colors) |
| print('purple' in colors) |
| |
| |
| if colors.count('blue') > 0: |
| print("Blue is in the tuple") |
| |
| |
| try: |
| position = colors.index('green') |
| print(f"Green found at position {position}") |
| except ValueError: |
| print("Green not found") |
- 添加元素的方法
元组不可变,不能直接添加元素,但可以创建新元组。
| original = (1, 2, 3) |
| |
| new_tuple = original + (4,) |
| print(new_tuple) |
| |
| |
| another = (*original, 5, 6) |
| print(another) |
# 字典 (dict)
字典是用于存储键值对的集合,键值对之间用冒号分隔,键值对之间用逗号分隔,字典用花括号 {} 表示。
| a = {"name": "Alice", "age": 25, "city": "New York"} |
| b = {1: "one", 2: "two", 3: "three"} |
初始化:
| |
| empty_dict = {} |
| empty_dict = dict() |
| |
| |
| person = {'name': 'Alice', 'age': 30, 'city': 'New York'} |
| squares = {1: 1, 2: 4, 3: 9, 4: 16} |
| |
| |
| squares = {x: x**2 for x in range(5)} |
| word_counts = {word: len(word) for word in ['apple', 'banana', 'cherry']} |
| |
| |
| from_list = dict([('name', 'Bob'), ('age', 25), ('city', 'Paris')]) |
| from_keys = dict.fromkeys(['a', 'b', 'c'], 0) |
| |
| |
| person = dict(name='Charlie', age=35, city='London') |
字典常见操作:
- 访问字典元素:使用键访问字典中的值。
| a = {"name": "Alice", "age": 25, "city": "New York"} |
| print(a["name"]) |
| print(a["age"]) |
| print(a["city"]) |
- 修改字典元素:使用键修改字典中的值。
| a = {"name": "Alice", "age": 25, "city": "New York"} |
| a["age"] = 26 |
| print(a) |
- 删除字典元素:使用
del
语句删除字典中的键值对。
| a = {"name": "Alice", "age": 25, "city": "New York"} |
| del a["age"] |
| print(a) |
- 字典长度:使用
len()
函数获取字典的长度。
| a = {"name": "Alice", "age": 25, "city": "New York"} |
| print(len(a)) |
- 字典遍历:使用
for
循环遍历字典中的键值对。
| a = {"name": "Alice", "age": 25, "city": "New York"} |
| for key, value in a.items(): |
| print(key, value) |
- 查找字典中元素:使用
in
运算符判断键是否在字典中。
| |
| person = {'name': 'Alice', 'age': 30, 'city': 'New York'} |
| |
| |
| print('name' in person) |
| print('email' in person) |
| |
| |
| print('New York' in person.values()) |
| print('London' in person.values()) |
| |
| |
| print(('name', 'Alice') in person.items()) |
| print(('age', 25) in person.items()) |
- 添加元素的方法
| |
| person = {"name": "Alice", "age": 30} |
| person["city"] = "New York" |
| print(person) |
| |
| |
| person = {"name": "Alice"} |
| person.update({"age": 30, "city": "Paris"}) |
| print(person) |
| |
| |
| person = {"name": "Alice"} |
| |
| age = person.setdefault("age", 25) |
| print(person) |
| |
| |
| squares = {x: x*x for x in range(1, 6)} |
| print(squares) |
# 集合 (set)
集合是用于存储多个元素的集合,元素不重复且无序。
| a = {1, 2, 3, 4, 5} |
| b = {"hello", "world"} |
| c = {1, "hello", 3.14} |
集合常见操作:
- 添加元素:使用
add()
方法向集合中添加元素。
| a = {1, 2, 3, 4, 5} |
| a.add(6) |
| print(a) |
- 删除元素:使用
remove()
方法从集合中删除指定元素。
| a = {1, 2, 3, 4, 5} |
| a.remove(3) |
| print(a) |
- 集合长度:使用
len()
函数获取集合的长度。
| a = {1, 2, 3, 4, 5} |
| print(len(a)) |
- 集合遍历:使用
for
循环遍历集合中的元素。
| a = {1, 2, 3, 4, 5} |
| for i in a: |
| print(i) |
- 集合交集:使用
&
运算符计算两个集合的交集。
| a = {1, 2, 3, 4, 5} |
| b = {4, 5, 6, 7, 8} |
| print(a & b) |
- 集合并集:使用
|
运算符计算两个集合的并集。
| a = {1, 2, 3, 4, 5} |
| b = {4, 5, 6, 7, 8} |
| print(a | b) |
- 集合差集:使用
-
运算符计算两个集合的差集。
| a = {1, 2, 3, 4, 5} |
| b = {4, 5, 6, 7, 8} |
| print(a - b) |
- 集合对称差集:使用
^
运算符计算两个集合的对称差集。
| a = {1, 2, 3, 4, 5} |
| b = {4, 5, 6, 7, 8} |
| print(a ^ b) |
# 布尔值
布尔值是用于表示真假的类型,只有两个值:True 和 False。
# 运算符
# 算术运算符
算术运算符用于执行基本的数学运算,例如加法、减法、乘法、除法等。
| a = 10 |
| b = 20 |
| c = a + b |
| d = a - b |
| e = a * b |
| f = a / b |
| g = a % b |
# 比较运算符
比较运算符用于比较两个值的大小关系,例如大于、小于、等于、不等于等。
| a = 10 |
| b = 20 |
| c = a > b |
| d = a < b |
| e = a == b |
| f = a != b |
# 逻辑运算符
逻辑运算符用于执行逻辑运算,例如与、或、非等。
| a = True |
| b = False |
| c = a and b |
| d = a or b |
| e = not a |
# 赋值运算符
赋值运算符用于将一个值赋给一个变量,例如等于、加等于、减等于等。
| a = 10 |
| b = 20 |
| a = b |
| a += b |
| a -= b |
| a *= b |
| a /= b |
| a %= b |
# 位运算
符号 |
功能 |
规则 |
& |
按位与 |
两个位都为 1 时,结果为 1 |
| |
按位或 |
两个位都为 0 时,结果为 0 |
^ |
按位异或 |
两个位不同时,结果为 1 |
~ |
按位取反 |
将所有位取反 |
<< |
左移 |
将所有位向左移动指定的位数 |
>> |
右移 |
将所有位向右移动指定的位数 |
| a = 60 |
| b = 13 |
| c = a & b |
| d = a | b |
| e = a ^ b |
| f = ~a |
| g = a << 2 |
| h = a >> 2 |
# 流程控制
# 条件语句
条件语句用于根据条件执行不同的代码块,例如 if 语句、if-else 语句、if-elif-else 语句等。
| a = 10 |
| b = 20 |
| |
| if a > b: |
| print("a大于b") |
| elif a < b: |
| print("a小于b") |
| else: |
| print("a等于b") |
# 循环语句
循环语句用于重复执行一段代码,例如 for 循环、while 循环等。
for
循环:用于遍历一个可迭代对象,例如 列表
、 元组
、 字符串
等。
| a = [1, 2, 3, 4, 5] |
| for i in a: |
| print(i) |
| |
| for i, ceil in enumerate(a): |
| print(ceil) |
- while 循环:用于在满足条件时重复执行一段代码。
| a = 1 |
| while a < 6: |
| print(a) |
| a += 1 |
# 函数
函数是一段可重复使用的代码块,可以接受参数并返回结果。
| def add(a, b): |
| return a + b |
| result = add(1, 2) |
| print(result) |
# 函数文档字符串
函数文档字符串用于描述函数的功能和用法,可以使用三引号 """
包围。
| def add(a, b): |
| """ |
| This function adds two numbers. |
| |
| Parameters: |
| a (int): The first number. |
| b (int): The second number. |
| |
| Returns: |
| int: The sum of the two numbers. |
| """ |
| return a + b |
# 函数参数
函数参数用于传递数据给函数。
- 位置参数:按照参数的顺序传递参数。
| def add(a, b): |
| return a + b |
| result = add(1, 2) |
| print(result) |
- 默认参数:为参数指定默认值。
| def add(a, b=2): |
| return a + b |
| result = add(1) |
| print(result) |
- 可变参数:使用
*
传递可变数量的参数。
| def add(*args): |
| |
| result = 0 |
| for i in args: |
| result += i |
| return result |
| result = add(1, 2, 3, 4, 5) |
| print(result) |
注意:函数接收可变数量的参数,使用 *args
接收参数, args
是一个元组类型 ()
。
- 关键字参数:通过
**
传递关键字参数。
| def fund(**kwargs): |
| |
| for key, value in kwargs.items(): |
| print(key, value) |
| fund(name="Alice", age=25, city="New York") |
注意:函数接收关键字参数,使用 **kwargs
接收参数, kwargs
是一个字典类型 {}
。
# 函数返回值
函数返回值用于返回函数执行的结果,可以使用 return
语句。
| def add(a, b): |
| return a + b |
| |
| result = add(1, 2) |
| print(result) |
# 函数嵌套
- 嵌套调用
函数嵌套调用是指在一个函数内部调用另一个函数。
| def add(a, b): |
| return a + b |
| |
| def multiply(a, b): |
| return a * b |
| |
| result = multiply(add(1, 2), 3) |
| print(result) |
- 嵌套定义
函数嵌套是指在一个函数内部定义另一个函数。
| def outer(): |
| def inner(): |
| print("This is inner function") |
| inner() |
| outer() |
# 匿名函数
匿名函数是指没有名字的函数,使用 lambda
关键字定义。
格式: 函数名 = lambda 参数列表: 表达式(返回值)
- 无参数匿名函数
| add = lambda: 1 + 2 |
| print(add()) |
- 有参数匿名函数
| add = lambda a, b: a + b |
| print(add(1, 2)) |
- 带默认参数匿名函数
| add = lambda a, b=2: a + b |
| print(add(1)) |
- 带可变参数匿名函数
| add = lambda *args: sum(args) |
| print(add(1, 2, 3, 4, 5)) |
- 带关键字参数匿名函数
| add = lambda **kwargs: sum(kwargs.values()) |
| print(add(a=1, b=2, c=3)) |
# 内置函数
内置函数是指 Python 语言自带的函数,例如 len()
、 max()
、 min()
等。
| a = [1, 2, 3, 4, 5] |
| print(len(a)) |
| print(max(a)) |
| print(min(a)) |
查看所有内置函数: dir(__builtins__)
dir
函数用于返回一个列表,包含指定对象的所有属性和方法。
| import math |
| print(dir(math)) |
| |
# map 函数
map 函数用于将一个函数应用于可迭代对象的每个元素,并返回一个迭代器。
格式: map(函数, 可迭代对象)
| a = [1, 2, 3, 4, 5] |
| result = map(lambda x: x * 2, a) |
| print(list(result)) |
# filter 函数
filter 函数用于过滤可迭代对象中的元素,并返回一个迭代器。
格式: filter(函数, 可迭代对象)
| a = [1, 2, 3, 4, 5] |
| result = filter(lambda x: x % 2 == 0, a) |
| print(list(result)) |
# reduce 函数
reduce 函数用于将一个函数应用于可迭代对象的每个元素,并返回一个值。
格式: reduce(函数, 可迭代对象)
| from functools import reduce |
| a = [1, 2, 3, 4, 5] |
| result = reduce(lambda x, y: x + y, a) |
| print(result) |
# zip 函数
zip 函数用于将多个可迭代对象中的元素打包成一个个元组,并返回一个迭代器。
格式: zip(可迭代对象1, 可迭代对象2, ...)
| a = [1, 2, 3] |
| b = ['a', 'b', 'c'] |
| result = zip(a, b) |
| print(list(result)) |
# 拆包
对于函数中的多个返回数据,去掉元组,列表或者字典的括号,直接赋值给多个变量。
| arr = [1, 2, 3] |
| a, b, c = arr |
| print(a) |
| print(b) |
| print(c) |
# 闭包
闭包是指在一个函数内部定义另一个函数,并且内部函数可以访问外部函数的变量。
| def outer(): |
| x = 10 |
| def inner(): |
| print(x) |
| return inner |
| closure = outer() |
| closure() |
# 作用域
作用域是指变量可访问的范围,分为全局作用域和局部作用域。
- 全局作用域:在函数外部定义的变量,可以在整个程序中访问。
| a = 10 |
| def add(b): |
| return a + b |
| result = add(5) |
| print(result) |
- 局部作用域:在函数内部定义的变量,只能在函数内部访问。
| def add(a, b): |
| c = a + b |
| return c |
| result = add(1, 2) |
| print(result) |
| print(c) |
** 注意:** 局部变量 c
只能在 add
函数内部访问,不能在函数外部访问。
局部变量升级为全局变量:使用 global
关键字声明变量为全局变量。
| a = 10 |
| def add(b): |
| global a |
| a = a + b |
| return a |
| result = add(5) |
| print(result) |
| print(a) |
局部变量 a
升级为全局变量,可以在函数外部访问。
# 异常
异常是指程序运行过程中出现的错误。
异常种类:
异常类型 |
描述 |
ZeroDivisionError |
除数为 0 |
TypeError |
类型错误 |
ValueError |
值错误 |
IndexError |
索引错误 |
KeyError |
键错误 |
NameError |
名称错误 |
AttributeError |
属性错误 |
SyntaxError |
语法错误 |
IndentationError |
缩进错误 |
IOError |
输入输出错误 |
EOFError |
文件结束错误 |
ImportError |
导入错误 |
ModuleNotFoundError |
模块未找到错误 |
AssertionError |
断言错误 |
KeyboardInterrupt |
键盘中断 |
SystemExit |
系统退出 |
Exception |
所有异常的基类 |
# 捕获异常。
示例:
| try: |
| a = 10 / 0 |
| except ZeroDivisionError: |
| print("除数不能为0") |
| try: |
| |
| except 异常类型1: |
| |
| finally: |
| |
- 格式四:try-except-else-finally
| try: |
| |
| except 异常类型1: |
| |
| except 异常类型2: |
| |
| else: |
| |
| finally: |
| |
# 抛出异常
使用 raise
关键字抛出异常。
格式: raise 异常类型(异常信息)
示例:
| def divide(a, b): |
| if b == 0: |
| raise ZeroDivisionError("除数不能为0") |
| return a / b |
| try: |
| result = divide(10, 0) |
| except ZeroDivisionError as e: |
| print(e) |
# 模块
模块是包含一组函数、类和变量的文件,可以导入到其他文件中使用。
# 内置模块
Python 内置了一些模块,可以直接使用,例如 math
、 random
、 datetime
等。
| import math |
| print(math.sqrt(16)) |
# 第三方模块(第三方库)
第三方模块是指由其他开发者编写的模块,需要先安装才能使用。
安装第三方模块:使用 pip
命令安装。
使用第三方模块:使用 import
关键字导入。
使用第三方模块中的函数:使用 模块名.函数名()
调用。
| import math |
| print(math.sqrt(16)) |
# 自定义模块
自定义模块是指用户自己编写的模块,需要先定义一个 .py
文件,然后在其他文件中导入使用。
注意:自定义模块的文件名不能与 Python 内置模块的文件名相同。
# 导入模块
- 导入模块:使用
import
关键字导入。
- 使用模块中的函数:使用
模块名.函数名()
调用。
| import math |
| print(math.sqrt(16)) |
- 导入模块中的特定函数:使用
from 模块名 import 函数名
导入。
| from math import sqrt |
| print(sqrt(16)) |
- 导入模块中的所有函数:使用
from 模块名 import *
导入。
| from math import * |
| print(sqrt(16)) |
- 导入模块中的特定变量:使用
from 模块名 import 变量名
导入。
| from math import pi |
| print(pi) |
# 起别名
# 模块起别名
使用 as
关键字给模块起别名。
语法: import 模块名 as 别名
| import math as m |
| print(m.sqrt(16)) |
# 功能起别名
使用 as
关键字给功能起别名。
语法: from 模块名 import 功能 as 别名
| from math import sqrt as s |
| print(s(16)) |
注意:导入多个功能时,可以使用‘,’隔开,后面功能也可以使用取别名: from math import sqrt as s, pi as p
# 内置全局变量
语法:
if name == “main”:
作用:用来控制 py 文件在不同应用场景下执行不同的逻辑,当模块被直接运行时, __name__
的值为 "__main__"
,当模块被导入时, __name__
的值为模块名。
例如:
| if __name__ == "__main__": |
| print("直接运行") |
| else: |
| print("被导入") |
直接运行该文件输出:
被导入该文件输出:
总结:导入不会执行 if __name__ == "__main__":
下的代码,只有直接运行该文件才会执行 if __name__ == "__main__":
下的代码。
包是指包含一组模块的文件夹,文件夹中必须包含一个 __init__.py
文件,用于标识该文件夹是一个包。
# init.py
使用包:使用 import 包名.模块名
导入。
| import mypackage.mymodule |
| print(mypackage.mymodule.myfunction()) |
使用包中的特定模块:使用 from 包名 import 模块名
导入。
| from mypackage import mymodule |
| print(mymodule.myfunction()) |
使用包中的特定函数:使用 from 包名.模块名 import 函数名
导入。
| from mypackage.mymodule import myfunction |
| print(myfunction()) |
使用包中的特定变量:使用 from 包名.模块名 import 变量名
导入。
| from mypackage.mymodule import myvariable |
| print(myvariable) |
使用包中的所有函数:使用 from 包名.模块名 import *
导入。
| from mypackage.mymodule import * |
| print(myfunction()) |
| print(myvariable) |
使用包中的所有变量:使用 from 包名.模块名 import *
导入。
注意:导包会默认执行 __init__.py
文件中的代码。
# all
__all__
是一个列表,用于指定包中可以被导入的模块。
语法: __all__ = ["模块名1", "模块名2", ...]
示例:
| |
| __all__ = ["mymodule1", "mymodule2"] |
使用包中的特定模块:使用 from 包名 import 模块名
导入。
| from mypackage import mymodule1 |
| print(mymodule1.myfunction()) |
# 闭包
闭包是指在一个函数内部定义的函数,它可以访问外部函数的局部变量。
实现:
- 函数嵌套(内部函数定义在外部函数内部)
- 内部函数访问外部函数的局部变量
- 外部函数返回内部函数
语法:
| def 外部函数(): |
| 变量 = 值 |
| def 内部函数(): |
| print(变量) |
| return 内部函数 |
示例:
| def outer_function(): |
| x = 10 |
| def inner_function(): |
| print(x) |
| return inner_function |
| |
| my_function = outer_function() |
| my_function() |
注意:闭包可以访问外部函数的局部变量,但是不能修改外部函数的局部变量。
# 函数引用
函数引用是指将函数赋值给一个变量,然后通过变量调用函数。
语法:
示例:
| def my_function(): |
| print("Hello, World!") |
| |
| my_function_ref = my_function |
| my_function_ref() |
# 闭包变量
闭包变量是指在闭包中使用的变量,闭包变量实际上只有一份,每次开启内函数都是在使用同一份闭包变量。
| def outer_function(n): |
| print("outer_function:", n) |
| def inner_function(m): |
| print("inner_function:",m) |
| return n + m |
| return inner_function |
| |
| out = outer_function(10) |
| out(20) |
| print(out(20)) |
# 装饰器
作用:在不修改原有函数代码的情况下,给函数增加新的功能。
- 标准装饰器
| |
| |
| |
| |
| |
| |
| def send(): |
| print("发送邮件") |
| |
| def outer_function(func): |
| def inner_function(): |
| print("before") |
| func() |
| print("after") |
| return inner_function |
| out = outer_function(send) |
| out() |
- 语法糖装饰器
| def outer_function(func): |
| def inner_function(): |
| print("before") |
| func() |
| print("after") |
| return inner_function |
| |
| @outer_function |
| def send(): |
| print("发送邮件") |
| |
| send() |
- 被装饰的函数有参数
| def outer_function(func): |
| def inner_function(*args, **kwargs): |
| print("before") |
| func(*args, **kwargs) |
| print("after") |
| return inner_function |
| |
| @outer_function |
| def send(name): |
| print("发送邮件给", name) |
| |
| send("张三") |
- 多个装饰器
| |
| def outer_function1(func): |
| def inner_function1(*args, **kwargs): |
| print("before1") |
| func(*args, **kwargs) |
| print("after1") |
| return inner_function1 |
| |
| def outer_function2(func): |
| def inner_function2(*args, **kwargs): |
| print("before2") |
| func(*args, **kwargs) |
| print("after2") |
| return inner_function2 |
| |
| @outer_function1 |
| @outer_function2 |
| |
| def send(name): |
| print("发送邮件给", name) |
| send("张三") |
注意:Python 的装饰器应用顺序是 自底向上
的,即靠近 函数定义
的装饰器( @outer_function2
)先被应用,外层装饰器( @outer_function1
)后应用。
以上可以看做: send = outer_function1(outer_function2(send))