7

I am new to python programming,I have one class,for this class i created one object( obj1).i don't want to create other than this object,if any body wants to create one more object for this class that should refer to first object only(instead of creating one more object).how to do this? please refer the below code?

class MyClass:
   def __init__(self):
      pass
obj1=MyClass()//create object
obj2=MyClass()//avoid creation and refer obj2 to obj1
obj3=MyClass()//avoid creation and refer obj3 to obj1
user1335578
  • 2,587
  • 2
  • 18
  • 15
  • 1
    Check this answer http://stackoverflow.com/questions/6760685/creating-a-singleton-in-python on singletons in python – Nick Craig-Wood Apr 29 '12 at 09:57
  • possible duplicate of [Is there a simple, elegant way to define Singletons in Python?](http://stackoverflow.com/questions/31875/is-there-a-simple-elegant-way-to-define-singletons-in-python) – Lennart Regebro Apr 29 '12 at 10:50
  • 2
    Off topic, but in Python comments start with a hash character (#). – martineau Apr 29 '12 at 15:02
  • Why is none of the answers to this question accepted yet? Just click on the outlied check mark on the left of your favourite answer... – glglgl May 22 '12 at 09:33

3 Answers3

8

So you want something singleton-ish? Then do not use objects for this at all. Simply put the functions in a separate module (.py file) and put your variables in the module scope (e.g. global variables) - that's the pythonic way to do what you want if you do not need thread safety. Remember: It's not java and using classes for everything is not the way to go.

However, here's some code that allows only one instance:

class MyClass:
    def __init__(self):
        if getattr(self.__class__, '_has_instance', False):
            raise RuntimeError('Cannot create another instance')
        self.__class__._has_instance = True

If you want singletons, have a look at Python and the Singleton Pattern and Is there a simple, elegant way to define singletons?

Community
  • 1
  • 1
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • 4
    In the same vein, though discussing other issues: [Python Is Not Java](http://dirtsimple.org/2004/12/python-is-not-java.html). –  Apr 29 '12 at 09:12
  • 1
    @delnan that was awesome. Good Comment – Jakob Bowyer Apr 29 '12 at 10:48
  • My +1 to using a module instead of the class. Classes and instances were actually created to be able to create more instances in comparison with modules. – pepr Apr 29 '12 at 19:35
3

Here's a simple way -- hide the class name:

class obj:
    pass

obj = obj()

Which will make class obj instances more difficult to create afterwards -- but not impossible, as pointed out in the comments.

Another alternative, delete the class after its first use:

class MyClass:
    def method(self): print 'spam'

obj1 = MyClass()
del MyClass
obj1.method()  # show instance still exists
obj2 = MyClass()

Output:

spam
Traceback (most recent call last):
  File "noclass.py", line 7, in <module>
    obj2 = MyClass()
NameError: name 'MyClass' is not defined
martineau
  • 119,623
  • 25
  • 170
  • 301
  • 3
    `obj2 = type(obj)()`. Actually, code like that is used from time to time for good reasons (and without ill intent), in metaprogramming code. –  Apr 29 '12 at 11:05
  • Yep, I've seen crazy stuff like this in ORM code and Python-to-other-language interfaces. – Matt Luongo May 03 '12 at 02:24
1

You could create the single object and make it a global i.e top-level object in the module using it if all you are coding would go in a single file or you could put it in a seperate module and import it.

cobie
  • 7,023
  • 11
  • 38
  • 60
  • This is not the solution. The singleton pattern mean that if any code (that is not aware of other parts of a program) *creates another* singleton object, it actually shares the only one without any other special means. The agreement to share a single object does not prevent other code to create another instance. – pepr Apr 29 '12 at 19:33