How to avoid object creation in python?
python, python-3.x
Solution
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?
Problem
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 ```