使用python中的构造函数限制在Singleton类中创建对象

时间:2019-04-26 04:35:11

标签: python object constructor singleton private

我正在为python中的要求之一编写单例类。我可以意识到,如果某些客户端先使用构造函数进行调用,然后再使用单例类方法(意味着该方法返回该类的唯一实例),则我将无法限制该类的对象创建。

这是什么意思?让我用一些代码片段来解释一下。 考虑我有以下示例之一:

public function index()
{
    $indicators =User::find(1)->indicator;
    $data = [];
    $data['indicators'] = $indicators;

    return view('pages.index', $data); // or return view('pages.index')->with($data);
}

如果运行上面的代码片段,则会得到如下结果:


import threading
class MyClass:

    __instance = None

    def __init__(self):

        if self.__instance:
            raise ValueError("Already exist")


    @classmethod
    def getInstance(cls):

        lock = threading.Lock()

        with lock:
            if cls.__instance == None:
                cls.__instance = MyClass()
            return cls.__instance

    def printObjInfo(self,obj):
        print(id(obj))


if __name__ == '__main__':

    ob4 = MyClass()
    ob4.printObjInfo(ob4)

    obj1 = MyClass.getInstance()
    obj1.printObjInfo(obj1)

    obj2 = MyClass.getInstance()
    obj2.printObjInfo(obj2)

    # Create a thread
    obj3 = MyClass.getInstance()
    obj3.printObjInfo(obj3)
    t1 = threading.Thread(target=obj3.printObjInfo, args=(obj3))

要注意的一件事-如果有人在调用 getInstance()方法之后调用了构造函数,那很好,我们可以轻松地限制其他对象的创建。但是,如果首先调用它,那么我们将无法控制它。

现在的问题是-1)我不能在__init __()中放置任何其他条件,以至于没有人调用此条件,或者2)无法将我的构造函数设为私有-我可以吗?

我在这里找到了一些参考-Changing a column data type 但不确定如何限制第一个对象的创建本身。有什么更好的方法可以让您做到这一点?

有什么想法或参考吗?

谢谢。

2 个答案:

答案 0 :(得分:1)

您可以改写__new__

class Singleton:

    _instance = None

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

    def __new__(cls, arg):
        if cls._instance is None:
            cls._instance = object.__new__(cls)
            return cls._instance

        else:
            return cls._instance

print(Singleton(None))
print(Singleton(None))
print(Singleton(None))

输出:

<__main__.Singleton object at 0x1207fa550>
<__main__.Singleton object at 0x1207fa550>
<__main__.Singleton object at 0x1207fa550>

这样做的好处是,存在一个用于创建和获取Singleton的单个实例的单一统一接口:构造函数。

请注意,除非您编写自己的C扩展名或类似的扩展名,否则您将永远无法在Python中创建真正的单例:

print(object.__new__(Singleton))
print(object.__new__(Singleton))
print(object.__new__(Singleton))

输出:

<__main__.Singleton object at 0x120806ac8>
<__main__.Singleton object at 0x1207d5b38>
<__main__.Singleton object at 0x1207d5198>

答案 1 :(得分:0)

基于 gmds 答案的线程安全单例版本

from multiprocessing.dummy import Pool as ThreadPool 
import threading
import time

class ThreadSafeSingleton:
    __instance = None
    __lock = threading.Lock()

    def __init__(self, *args, **kwargs):
        self.args = args
        self.kwargs = kwargs

    def __str__(self):
        return 'id: {}, args: {}, kwargs: {}'.format(id(self), self.args, self.kwargs)

    def __new__(cls, *args, **kwargs):
        with cls.__lock:
            if cls.__instance is None:
                # sleep just simulate heavy class initialization  !!
                # process under concurrency circumstance          !!
                time.sleep(1)
                print('created')
                cls.__instance = super(ThreadSafeSingleton, cls).__new__(cls)
            return cls.__instance


class ThreadUnsafeSingleton:
    __instance = None

    def __init__(self, *args, **kwargs):
        self.args = args
        self.kwargs = kwargs

    def __str__(self):
        return 'id: {}, args: {}, kwargs: {}'.format(id(self), self.args, self.kwargs)

    def __new__(cls, *args, **kwargs):
        if cls.__instance is None:
            time.sleep(1)
            print('created')
            cls.__instance = super(ThreadUnsafeSingleton, cls).__new__(cls)
        return cls.__instance


def create_safe(*args, **kwargs):
    obj = ThreadSafeSingleton(*args, **kwargs)
    print(obj)


def create_unsafe(*args, **kwargs):
    obj = ThreadUnsafeSingleton(*args, **kwargs)
    print(obj)


if __name__ == '__main__':
    pool = ThreadPool(4)
    print('---- test thread safe singleton  ----')
    pool.map(create_safe, range(10))

    print('\n---- test thread unsafe singleton  ----')
    pool.map(create_unsafe, range(10))

输出:

---- test thread safe singleton  ----
created
id: 4473136352, args: (0,), kwargs: {}
id: 4473136352, args: (1,), kwargs: {}
id: 4473136352, args: (2,), kwargs: {}
id: 4473136352, args: (4,), kwargs: {}
id: 4473136352, args: (5,), kwargs: {}
id: 4473136352, args: (3,), kwargs: {}
id: 4473136352, args: (6,), kwargs: {}
id: 4473136352, args: (7,), kwargs: {}
id: 4473136352, args: (8,), kwargs: {}
id: 4473136352, args: (9,), kwargs: {}

---- test thread unsafe singleton  ----
created
id: 4473136968, args: (0,), kwargs: {}
created
created
created
id: 4473136968, args: (4,), kwargs: {}
id: 4473137024, args: (2,), kwargs: {}
id: 4473137080, args: (1,), kwargs: {}
id: 4473137136, args: (3,), kwargs: {}
id: 4473137136, args: (5,), kwargs: {}
id: 4473137136, args: (7,), kwargs: {}
id: 4473137136, args: (6,), kwargs: {}
id: 4473137136, args: (8,), kwargs: {}
id: 4473137136, args: (9,), kwargs: {}