Singleton: Difference between revisions

→‎{{header|Python}}: - actual singleton implementation in Python
(→‎{{header|Python}}: - actual singleton implementation in Python)
Line 1,616:
True
>>> # For any datum!</lang>
 
An approximation of the singleton can be made using only class attributes to store data instead of the instance attributes, providing at least one abstract instance method (class can not be instantiated then) and making the rest of the methods being class methods. E.g.
 
<lang python>
import abc
 
class Singleton(object):
"""
Singleton class implementation
"""
__metaclass__ = abc.ABCMeta
state = 1 #class attribute to be used as the singleton's attribute
@abc.abstractmethod
def __init__(self):
pass #this prevents instantiation!
@classmethod
def printSelf(cls):
print cls.state #prints out the value of the singleton's state
 
#demonstration
if __name__ == "__main__":
try:
a = Singleton() #instantiation will fail!
except TypeError as err:
print err
Singleton.printSelf()
print Singleton.state
Singleton.state = 2
Singleton.printSelf()
print Singleton.state
</lang>
When executed this code should print out the following:<br>
<br>
Can't instantiate abstract class Singleton with abstract methods __init__<br>
1<br>
1<br>
2<br>
2<br>
<br>
So, instantiation is not possible. Only a single object is available, and it behaves as a singleton.
 
=={{header|PureBasic}}==