mercredi 20 janvier 2016

Singleton- python, Situation with the need of only one object

I am having a situation where I have to make sure I only have one object. I am thinking about implementing singleton like following:

class One_Of_a_Kind:
    def __init__(self):
        self.do_some_setup()


class One_Creator:
    Only_One = None
    def __new__(cls, *args, **kwargs):
        if One_Creator.Only_One:
            return One_Creator.Only_One
        else:
            One_Creator.Only_One = One_of_a_Kind()
            return One_Creator.Only_One

Since I am reading a lot about singleton (pros and cons), I am little hesitant in implementing this code. I would like to know if it is okay and/or considered good practice to use in a situation where only one object of certain class in needed ( or mandatory).

Is there a better way of implementing the same thing?

Aucun commentaire:

Enregistrer un commentaire