0

For a class in python how to implement singleton properties to it.Please provide an example for the following class.What i am basically trying to understand is that if an instance of the class exist then it should return the existing instance else create an instance of that class

  class Test:
     name
     age

     def getobj(self):
        return (self.name+self.age)

    t= Test()
Hulk
  • 32,860
  • 62
  • 144
  • 215

2 Answers2

7

You should not implement singleton as a class. Use a module, that works great as a singleton.

Also: Is there a simple, elegant way to define singletons?

Community
  • 1
  • 1
gruszczy
  • 40,948
  • 31
  • 128
  • 181
  • why not implement Singleton as a class? – Alcott Sep 20 '11 at 00:10
  • You can do that, but since a module can act exactly as you need, why bother? Unlike in C++ or Java you can't force user not to create more instances of your singleton (everything is public or mangled, but still accessible). Using a module lets you create a real singleton, that exists only in one instance. – gruszczy Sep 21 '11 at 08:33
2

I personally wouldn't use a singleton design pattern on such a class, as with a singleton you are ensuring that there is, and only ever will be one of them. Why would you only ever want one Employee?

You could say have it on say, an employeeManager, or an employeeList, even if i'm not a huge fan of having it on those either.

Dan
  • 41
  • 3