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
The object is essential to work with the class attributes. Instantiate is a term used when we create the object of any class, and the instance is also referred to as an object. The object is created using the class name. The syntax is given below.
Yes, we can execute a java program without a main method by using a static block.
Creating an object in Python The object is created using the name of the class. The object shares all the behavior and attributes of the class, such as the variables and values present in the class. Also, the object inherits the functions mentioned in the class, along with the class's behavior.
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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With