Welcome, guest | Sign In | My Account | Store | Cart

Yet one singleton realization on Python without metaclass. Singleton may has __init__ method which will call only when first object create.

Python, 25 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Singleton(object):
        
    def __new__(cls,*dt,**mp):
        if not hasattr(cls,'_inst'):
            cls._inst = super(Singleton, cls).__new__(cls,dt,mp)
        else:
            def init_pass(self,*dt,**mp):pass
            cls.__init__ = init_pass
            
        return cls._inst
    
if __name__ == '__main__':
    
    
    class A(Singleton):
    
        def __init__(self):
            """Super constructor
                There is we can open file or create connection to the database
            """
            print "A init"
        
        
    a1 = A()
    a2 = A()
Created by Dmitry on Fri, 23 Apr 2010 (MIT)
Python recipes (4591)
Dmitry's recipes (3)

Required Modules

  • (none specified)

Other Information and Tasks