闭包
在函数嵌套的前提下,内部函数使用了外部函数的变量,并且外部函数返回了内部函数,我们把这个使用外部函数变量的内部函数称为闭包。
def outfunc(arg):
def innerFunc(msg):
print(f"<{msg}> {arg} <{msg}>")
return innerFunc
func = outfunc("尔")
func("沃")
def outfunc(num1):
def innerFunc(num2):
nonlocal num1
num1 += num2
return num1
return innerFunc
func = outfunc(10)
print(func(20))
print(func(30))
nonlocal关键字的作用
在闭包函数想要修改外部函数变量的值 需要用nonlocal 声明这个外部变量
闭包的优点
无需定义全局变量即可实现通过函数,持续的访问修改某个值。
闭包使用的变量的作用域在函数内 难以被错误的调用修改。
缺点:
由于内部函数持续引用外部函数的值,所以会导致这一部分内存空间不被释放一直占用内存。
装饰器
装饰器也是一种闭包,其功能就是在不破坏目标函数原有的代码和功能的前提下为目标函数增加新功能。
def doworking():
print("do working")
def outfunc(func):
def innerFunc():
print("开始上班")
func()
print("下班回家")
return innerFunc
action = outfunc(doworking)
action()
语法糖
def outfunc(func):
def innerFunc():
print("开始上班")
func()
print("下班回家")
return innerFunc
@outfunc
def doworking():
print("do working")
doworking()
设计模式
单例模式
程序运行时一个类无论创建多少次 只有一个对象
class DatabaseManager:
pass
data_manager = DatabaseManager()
from singleObj import data_manager
manager1 = data_manager
manager2 = data_manager
print(id(manager1))
print(id(manager2))
工厂模式
class Animal:
pass
class Dog(Animal):
pass
class Cat(Animal):
pass
class Pig(Animal):
pass
class AnimalFactory:
def get_animal(self,type):
if type == "d":
return Dog()
elif type == "c":
return Cat()
elif type == "P":
return Pig()
else:
return Animal()
factory = AnimalFactory()
pig = factory.get_animal("p")
dog = factory.get_animal("d")
cat = factory.get_animal("c")
wolf = factory.get_animal("w")
print(f"pigtype={type(pig)} dogtype={type(dog)} cattype={type(cat)} wolftype = {type(wolf)}")
线程。进程
import time
import threading
def game():
while True:
print("进攻敌方防御塔")
time.sleep(1)
def music():
while True:
print("对面的女孩 看过来")
time.sleep(1)
gameThread = threading.Thread(target=game)
musicThread = threading.Thread(target=music)
gameThread.start()
musicThread.start()
time.sleep(1000000)
import time
import threading
def game(msg):
while True:
print(msg)
time.sleep(1)
def music(msg):
while True:
print(msg)
time.sleep(1)
gameThread = threading.Thread(target=game,args=("进攻敌方防御塔",))
musicThread = threading.Thread(target=music, kwargs={"msg":"对面的女孩 看过来"})
gameThread.start()
musicThread.start()
time.sleep(1000000)