Python: thinking of a module and its variables as a singleton — Clean approach?

后端 未结 6 2098
被撕碎了的回忆
被撕碎了的回忆 2020-12-13 13:21

I\'d like to implement some sort of singleton pattern in my Python program. I was thinking of doing it without using classes; that is, I\'d like to put all the singleton-rel

6条回答
  •  一向
    一向 (楼主)
    2020-12-13 13:34

    For a legitimate Singleton:

    class SingletonMeta(type):
        __classes = {} # protect against defining class with the same name
        def __new__(cls, cls_name, cls_ancestors, cls_dict): 
             if cls_name in cls.__classes:
                 return cls.__classes[cls_name]
             type_instance = super(SingletonMeta, cls).__new__(cls, cls_name, cls_ancestors, cls_dict) # pass 'type' instead of 'cls' if you dont want SingletonMeta's attributes reflected in the class
             return type_instance() # call __init__
    
    class Singleton:
        __metaclass__ = SingletonMeta
        # define __init__ however you want
    
        __call__(self, *args, *kwargs):
            print 'hi!'
    

    To see that it truly is a singleton, try to instantiate this class, or any class that inherits from it.

    singleton = Singleton() # prints "hi!"
    

提交回复
热议问题