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
4
  • 1
    Check this answer stackoverflow.com/questions/6760685/… on singletons in python Commented Apr 29, 2012 at 9:57
  • possible duplicate of Is there a simple, elegant way to define Singletons in Python? Commented Apr 29, 2012 at 10:50
  • 2
    Off topic, but in Python comments start with a hash character (#). Commented Apr 29, 2012 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... Commented May 22, 2012 at 9:33

3 Answers 3

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?

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

3 Comments

In the same vein, though discussing other issues: Python Is Not Java.
@delnan that was awesome. Good Comment
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.
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

2 Comments

obj2 = type(obj)(). Actually, code like that is used from time to time for good reasons (and without ill intent), in metaprogramming code.
Yep, I've seen crazy stuff like this in ORM code and Python-to-other-language interfaces.
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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.