Python中的设计模式
2021/11/28 20:44:14
本文主要是介绍Python中的设计模式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
设计模式
- 单例模式
单例模式
- 使用类名()创建对象时,解释器默认调用类的__new__()方法为其分配内存,并返回对象的引用
- 解释器获得对象的引用后,会将其传给__init__()的self参数,执行初始化动作
- 单例:重写__new__()方法 + 只执行一次初始化动作
class Player(object): instance = None # 类属性,记录单例对象的引用 init_flag = False # 类属性,记录是否执行过初始化动作 def __new__(cls, *args, **kwargs): """懒汉单例""" if cls.instance is None: cls.instance = super().__new__(cls) return cls.instance def __init__(self): if Player.init_flag: # 让初始化动作只执行一次 return print("初始化") Player.init_flag = True # 二者是同一个对象,且只执行了一次初始化动作 p1 = Player() p2 = Player() print(p1) # 初始化 # <__main__.Player object at 0x000001E87B3FB100> print(p2) # <__main__.Player object at 0x000001E87B3FB100>
这篇关于Python中的设计模式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python