python 面试相关

python单例模式:

    Python真的需要单例模式吗?我指像其他编程语言中的单例模式。 

    答案是:不需要!  因为,Python有模块(module),最pythonic的单例典范。模块在在一个应用程序中只有一份,它本身就是单例的,将你所需要的属性和方法,直接暴露在模块中变成模块的全局变量和方法即可   

#!/usr/bin/env python
#encoding=utf-8

import threading

#单例类
class Singleton(object):
    instance = None
    mutex =threading.Lock()
    def __init__(self):
        pass

    @ staticmethod  #声明这个是静态方法
    def GetInstance():
        if(Singleton.instance == None):
            Singleton.mutex.acquire()
            if(Singleton.instance == None):
                print "init the instance"
                Singleton.instance = Singleton()
            else:
                print "init the instance already"
            Singleton.mutex.release()
        else:
            print "init the instance already"
        return Singleton.instance

if __name__ == '__main__':
    Singleton.GetInstance()
    Singleton.GetInstance()
    Singleton.GetInstance()
#类只能调用到静态的方法,切记

 

转载于:https://www.cnblogs.com/chris-cp/p/3765964.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值