python中的__new__方法和单例设计模式


#1. __new__方法

# 创建对象(__new__) =》 初始化对象(__init__)


class Car(object):
	#__new__方法是类方法
	def __new__(cls,*args,**kwargs):
		print('new method')
		# 一定要切记,必须要在new方法后面返回当前这个类的对象
		#因为__new__方法是来创建对象的
		return super(Car,cls).__new__(cls,*args,**kwargs)

	def __init__(self):
		print('car init method')


car=Car()
print(car)

#2.单例设计模式:某个类或者模型在整个程序运行期间最多只能有一个对象被创建
#我们可以判断,如果User这个类没有创建过对象,那么就创建一个对象保存在某个地方
#以后如果要再创建对象,我会去判断,如果之前已经创建了一个对象,那么就不再创建
#而是直接把之前那个对象返回回去
#__new__方法创建对象

class User(object):

	__instance = None
	
	def __new__(cls,*args,**kwargs):
		if not cls.__instance:
			cls.__instance = super(User,cls).__new__(cls)
		return cls.__instance

	def __init__(self,name):
		self.name = name

	
user1 = User('luobin')
user2 = User('fjq')

#判断两个对象是否属于同一个对象,通过调用id()来查看他们的id
#若一样,则两个对象就是同一个对象。
print(id(user1))
print(id(user2))


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
回答: 在Python,可以使用模块来实现单例设计模式。因为模块在第一次导入时会生成.pyc文件,当第二次导入时会直接加载.pyc文件,而不会再次执行模块代码。所以,我们只需要把相关的函数和数据定义在一个模块,就可以获得一个单例对象了。\[1\] 另外,我们也可以通过在类的__new__方法实现单例模式。在__new__方法,我们可以控制对象的创建过程,确保只有一个实例被创建。可以使用线程锁来保证在多线程环境下的线程安全性。\[3\] 以下是一个使用共享属性版本实现的单例模式的示例代码: ```python # s1.py class Singleton(object): def __new__(cls, *args, **kwargs): if not hasattr(cls, "_instance"): cls._instance = super().__new__(cls, *args, **kwargs) return cls._instance # s2.py from s1 import Singleton a = Singleton() b = Singleton() print(id(a)) # 输出相同的id print(id(b)) # 输出相同的id ``` 这样,无论创建多少个Singleton的实例,都会得到同一个实例对象。\[2\] #### 引用[.reference_title] - *1* *3* [Python单例模式的几种实现方式的及优化](https://blog.csdn.net/aobian2884/article/details/101404352)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [Python 单例模式](https://blog.csdn.net/hj1993/article/details/129209110)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值