How to adapt the Singleton pattern? (Deprecation warning)

后端 未结 3 1117
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-07 11:18

Few years ago I found an implementation of the Singleton pattern in Python by Duncan Booth:

class Singleton(object):
    \"\"\"
    Singleton class by Duncan Boo         


        
3条回答
  •  梦毁少年i
    2021-02-07 11:57

    So based on the answers from @Sven and @Duncan I found a solution which works for me. The problem actually wasn't in the line of the code raising the TypeError, but in the signature of the __new__() method. The call of the object.__new__(cls) shall be without the *args, **kwargs, but they have to remain in the Singleton.__new__() definition. This is the modified Singleton:

    class Singleton(object):
        """
        Singleton class by Duncan Booth.
        Multiple object variables refers to the same object.
        http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html
        """
       _instance = None
    
        def __new__(cls, *args, **kwargs):
            if not cls._instance:
                cls._instance = super(Singleton, cls).__new__(cls)
            return cls._instance
    

    And this is an example of sub-classing (which was the issue):

    class Child(Singleton):  
        def __init__(self,param=None):  
                print param  
                print 'Doing another stuff'  
    
    ch=Child('Some stuff')
    

    I still don't understand why the signature of Child's __init__() has to match to Singleton's `new(), but this solution works.

提交回复
热议问题