定义双层嵌套函数,内层函数可以访问外层函数的变量
将内层函数作为外层函数的返回,此层函数就是闭包函数
在函数嵌套的前提下,内部函数使用了外部函数的变量,并且外部函数返回了内部函数,我们把这个使用外部函数变量的内部函数称为闭包
def outer(logo):
def inner(msg):
print(f"{logo}:{msg}")
return inner
fun = outer("java")
fun("hello world")
闭包修改外部函数的值
需要用 nonlocal 声明这个外部变量
def outer(num1):
def inner(num2):
nonlocal num1
num1 += num2
print(num1)
return inner
fun = outer(10)
fun(10) # 输出20
优点:
- 无需定义全局变量即可实现通过函数,持续的访问、修改某个值
- 闭包使用的变量的所用于在函数内,难以被错误的调用修改
缺点:
- 由于内部函数持续引用外部函数的值,所以会导致这一部分内存空间不被释放,一直占用内存
装饰器其实也是一种闭包,其功能就是在不破坏目标函数原有的代码和功能的前提下,为目标函数增加新功能
def outer(func):
def inner():
print("我要睡觉了")
func()
print("我起床了")
return inner
@outer
def sleep():
print("睡眠中")
sleep()
# 单例
def strTool():
pass
signle = strTool()
#==
from 单例 import signle
t1 = signle
t2 = signle
print(id(t1))
print(id(t2))
将对象的创建由使用原生类本身创建转换到由特定的工厂方法来创建
好处:
- 大批量创建对象的时候有统一的入口,易于代码维护
- 当发生修改,仅修改工厂类的创建方法即可
class Person:
pass
class Worker(Person):
pass
class Student(Person):
pass
class Teacher(Person):
pass
class PersonFactory:
def get_person(self,p_type):
if p_type == 'w':
return Worker()
elif p_type == 's':
return Student()
else:
return Teacher()
pf = PersonFactory()
worker = pf.get_person('w')
student = pf.get_person('s')
teacher = pf.get_person('t')
threading模块使用
import threading
import time
def sing(msg):
print(msg)
time.sleep(1)
def dance(msg):
print(msg)
time.sleep(1)
if __name__ == '__main__':
sing_thread = threading.Thread(target=sing,args=("唱歌。。。",))
dance_thread = threading.Thread(target=dance,kwargs={"msg":"跳舞。。。"})
sing_thread.start()
dance_thread.start()
Socket(套接字)是进程间通信工具
服务端
# 创建Socket对象
import socket
socket_server = socket.socket()
# 绑定IP地址和端口
socket_server.bind(("localhost", 8888))
# 监听端口
socket_server.listen(1)
# 等待客户端链接
conn, address =socket_server.accept()
print(f"接收到客户端的信息{address}")
while True:
data: str = conn.recv(1024).decode("UTF-8")
print(f"客户端消息{data}")
# 发送回复消息
msg = input("输入回复消息:")
if msg == 'exit':
break
conn.send(msg.encode("UTF-8"))
# 关闭连接
conn.close()
socket_server.close()
客户端、
import socket
# 创建socket对象
socket_client = socket.socket()
# 连接到服务器
socket_client.connect(("localhost", 8888))
while True:
msg = input("输入发送消息:")
if(msg == 'exit'):
break
# 发送消息
socket_client.send(msg.encode("UTF-8"))
#接收返回消息
recv_data = socket_client.recv(1024)
print(f"服务端回复消息:{recv_data.decode('UTF-8')}")
# 关闭链接
socket_client.close()
import re
s = "pythonxxxxxxpython"
result = re.match("python",s) # 从左到右匹配
print(result) #
print(result.span()) # (0, 6)
print(result.group()) # python
result = re.search("python",s) # 匹配到第一个
print(result) #
result = re.findall("python",s) # 匹配全部
print(result) # ['python', 'python']
单字符匹配
数量匹配
边界匹配
分组匹配
pattern = "1[35678]\d{9}"
phoneStr = "15288888888"
result = re.match(pattern, phoneStr)
print(result) #
递归显示目录中文件
import os
def get_files_recursion_dir(path):
file_list = []
if os.path.exists(path):
for f in os.listdir(path):
new_path = path + "/" + f
if os.path.isdir(new_path):
file_list += get_files_recursion_dir(new_path)
else:
file_list.append(new_path)
else:
print(f"指定的目录{path},不存在")
return []
return file_list
if __name__ == '__main__':
print(get_files_recursion_dir("D:\test"))