How to adapt the Singleton pattern? (Deprecation warning)

后端 未结 3 1115
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  借酒劲吻你
    2021-02-07 11:40

    You need to drop any additional arguments you are passing when you construct the object. Change the offending line to:

            cls._instance = object.__new__(cls)
    

    or

            cls._instance = super(Singleton, cls).__new__(cls)
    

    though I think you'll be fine with the first (diamond inheritance and singletons sound as though they shouldn't be mixed).

    P.S. I did try this suggestion and it works for me so I don't know why it didn't work for you.

    Edit in response to @dragonx's comment: As pointed out in the comments, object.__new__ will throw an exception if you pass on *args, **kwargs so the super call to __new__ should not include any arguments apart from cls. This wasn't the case when the original article was written. Also of course if you choose to base your singleton on some other type such as a tuple you would then need to pass the appropriate arguments.

提交回复
热议问题