How to avoid creating an object in python?

I am new to python programming, I have one class, for this class I created one object (obj1) .i I do not want to create anything other than this object if any body wants to create another object for this class that must reference only on the first object (instead of creating another object). How to do it? please refer to the code below?

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
+5
source share
3 answers

, - ? . (.py ) (, ) - , , . : java, - .

, :

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

, Python Singleton , ?

+7

- :

class obj:
    pass

obj = obj()

class obj , , .

, :

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

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

:

spam
Traceback (most recent call last):
  File "noclass.py", line 7, in <module>
    obj2 = MyClass()
NameError: name 'MyClass' is not defined
+3

You can create a single object and make it global, i.e. a top-level object in a module, using it if everything you encode is in one file, or you can put it in a separate module and import it.

+1
source

All Articles