python实现单例模式的常用三种方法-基于__new__/使用装饰器以及Python中的值类型、引用类型以及类的静态变量、读取进程和线程ID

一、python实现单例模式的常用三种方法-基于__new__,使用装饰器

        涉及到类的使用就会有类的实例化,就会有类单例实现的需求,因为重复实例化会浪费资源。python中的单例模式与别的语言相比,单例实现的方法更丰富。虽然python实现单例的模式的方法有很多,不过在体验后我觉得有必要了解和掌握的也就是使用模块和使用装饰器两种,然后了解一下使用__new__方法实现单例。

1. 使用python模块

        Python模块本身就包含了一个单例实现逻辑,在第一次导入时,会生成.pyc文件,之后导入,就会直接加载.pyc,因此如果在我们在模块中new实例对象,然后在其它的地方直接引用生成的对象,就是单例模式了,python模块singleton.py内容如下:

#模块中的方法
class Singleton(object):
    def test(self):
        print("test")

#直接初始化类	
singleton = Singleton()

在其它的地方使用时,直接导入此文件中的对象即是单例模式的对象
from singleton import singleton

2. 使用__new__方法

        因为python实例化对象的逻辑是先执行类的__new__方法(默认调用object.__new__)实例化对象,再执行类的__init__方法对这个对象进行初始化,所有我们可以在__new__方法中进行控制以实现单例模式,代码示例如下:

class Singleton(object):
    
    def __init__(self):
        pass

    def __new__(cls, *args, **kwargs):
        if not hasattr(Singleton, "_instance"):
			if not hasattr(Singleton, "_instance"):
				Singleton._instance = object.__new__(cls)  
        return Singleton._instance

3. 使用装饰器实现单例模式

        上面的使用__new__方法需要在每个类中去定义方法体,而使用装饰器则可以实现定义一个方法体,然后装饰给所有我们要实现单例模式的类即可,重复利用并简化代码。推荐使用第3种方法.

#定义一个单例方法
def Singleton(cls):
    _instance = {}

    def _singleton(*args, **kargs):
        if cls not in _instance:
            _instance[cls] = cls(*args, **kargs)
        return _instance[cls]

    return _singleton

#装饰给所有我们要实现单例模式的类即可
@Singleton
class Test(object):
    def test_fun(self):
		pass

        关于线程安全的单例模式,上述第2、3种方法能实现单例模式,但并不是线程安全的单例模式,如果有需求实现线程安全,可以进行改造,添加threading模块并进行加锁控制。示例如下。

# 使用__new__方法创建基于线程安全的单例模式
import threading
class Singleton(object):
    _instance_lock = threading.Lock()

    def __init__(self):
        pass

    def __new__(cls, *args, **kwargs):
        if not hasattr(Singleton, "_instance"):
            with Singleton._instance_lock:
                if not hasattr(Singleton, "_instance"):
                    Singleton._instance = object.__new__(cls)  
        return Singleton._instance
		
# 使用__new__方法创建基于线程安全的单例模式	
import threading
def Singleton(cls):
    _instance = {}
	lock = threading.Lock()

    def _singleton(*args, **kargs):
		with lock:
			if cls not in _instance:
				_instance[cls] = cls(*args, **kargs)
        return _instance[cls]

    return _singleton

#装饰给所有我们要实现单例模式的类即可
@Singleton
class Test(object):
    def test_fun(self):
		pass

        关于多线程模块,thread模块已被废弃,在Python3中不能再使用thread模块。用户可以使用threading模块代替。

二、Python中的值类型、引用类型以及类的-静态-变量

        Python中的数据类型分为值类型和引用类型,值类型通常包含int、float、bool、str、tuple,值类型是不可变的。引用类型包含list、set、dict类型,引用类型是可变的。在python的面向对象中,类不存在像其它语言中存在的static关键词,因此不能使用修饰实现类的静态变量。python面向对象中只有实例变量和类变量两变量概念,根本不存在静态变量的概念。

        接下来我们来看下面这个例子以及其运行结果,结果中有横线来区分开每个执行结果,比较好分别,如下:

#定义四个方法,各操作一些属性
class task1:
    value=1
    def increment(self):
        self.value += 1

class task2:
    value=[]
    def increment(self):
        self.value.append(1)

class task3:
    def __init__(self):
        self.value=[]
    def increment(self):
        self.value.append(1)

class task4:
    value=1
    def increment(self):
        self.value += 1
		
#分别调用四个方法	
if __name__=="__main__":
    a=task1()
    b=task1()
    a.increment()
	print(a.value)
    print(b.value)
    print('-'*30)
	
	a=task2()
    b=task2()
    a.increment()
	print(a.value)
    print(b.value)
    print('-'*30)
	
	a=task3()
    b=task3()
    a.increment()
	print(a.value)
    print(b.value)
    print('-'*30)
	print('-'*30)

    a=task4()
    b=task4()
    task4.value+=1
    print(a.value)
	print(b.value)
    a.increment()
    print(a.value)
    print(b.value)
    print(task4.value)

程序运行结果如下:

===========运行结果=================
2
1
------------------------------
[1]
[1]
------------------------------
[1]
[]
------------------------------
2
2
3
2
2

第1个示例应该如我们预期,只改变了a而b的没有变更。
第2个示例和第1个基本相同,但结果却是a和b都同时发生了改变。
第3个示例在2示例上做了一些改变,从而符合我们的预期。
第4个示例我们改变了task4的属性,其它的类的属性有的有影响,有的却没有影响。
是为什么呢?
    第1个和第2个示例的相同点是都是类的属性,但一个是值类型,一个是引用类型。引用类型的类变量就如同我们其它语言的静态变量,尽管python没有静态变量的概念,但这样操作就实现了静态变量的功能。第3个示例和第2个的区别是第3个用的是实例的变量,所以各自归各自管理。第4个示例,实例化a和b的时候,他们都没有对属性value进行操作,所以打印出来的都是类task4的属性value,而在对象对自己的value进行操作之后,就与类的属性脱离关系,变成自己的属性。 

三、Python中读取程序中的进程和线程ID

    程序调试的时候有时需要看看当前程序的进程和线程ID,可以使用如下的方法。

#引入OS和psutil库
import os
import psutil
import threading

#取得python进程数据
pid = os.getpid()
p = psutil.Process(pid)
print('PID: %d' % pid)
print('PNAME: %s' % p.name())
print(p.__dict__)

#取得线程ID数据
t = threading.currentThread()
print("TID: %d" % t.ident)
print("TID: %d" % t.name)
print("TNAME: %S" % t.getName())
print(t.__dict__)

#print(p)打印出来的结果
psutil.Process(pid=14572, name='python.exe', status='running', started='18:46:27')
#print(p.__dict__)打印出来的结果格式化之后
{
	'_pid': 15144,
	'_name': 'python.exe',
	'_exe': None,
	'_create_time': 1629788019.0382779,
	'_gone': False,
	'_hash': None,
	'_lock': < unlocked _thread.RLock object owner = 0 count = 0 at 0x0000020F41511840 > ,
	'_ppid': None,
	'_proc': < psutil._pswindows.Process object at 0x0000020F416E4700 > ,
	'_last_sys_cpu_times': None,
	'_last_proc_cpu_times': None,
	'_exitcode': < object object at 0x0000020F41BAE470 > ,
	'_ident': (15144, 1629788019.0382779)
}

#print(t)打印出来的结果
<_MainThread(MainThread, started 15280)>
#print(t.__dict__)打印出来的结果格式化之后
{
	'_target': None,
	'_name': 'MainThread',
	'_args': (),
	'_kwargs': {},
	'_daemonic': False,
	'_ident': 7652,
	'_native_id': 7652,
	'_tstate_lock': < locked _thread.lock object at 0x000002A0A834AA20 > ,
	'_started': < threading.Event object at 0x000002A0A834A7F0 > ,
	'_is_stopped': False,
	'_initialized': True,
	'_stderr': < _io.TextIOWrapper name = '<stderr>'
	mode = 'w'
	encoding = 'gbk' > ,
	'_invoke_excepthook': < function _make_invoke_excepthook. < locals > .invoke_excepthook at 0x000002A0A8352CA0 >
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

林戈的IT生涯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值