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()
3
  • Is this homework? What have you tried? Commented Mar 21, 2011 at 20:41
  • 6
    Singletons and Employees? What. Commented Mar 21, 2011 at 20:42
  • 2
    See this. Commented Mar 21, 2011 at 20:44

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

2 Comments

why not implement Singleton as a class?
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.
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.

1 Comment

If an emp object is set then i need not create one.That was the objective

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.