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

Here I have implemented the Singleton base class using __new__. I was reading thru Bruce Eckel's http://www.mindview.net/Books/TIPython and thought OnlyOne can be more simple....

Are there any differences in between two approaches?

Python, 20 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class OnlyOne(object):
    """
    Signleton class , only one obejct of this type can be created
    any class derived from it will be Singleton
    """
    __instance = None
    def __new__(typ, *args, **kwargs):
        if OnlyOne.__instance == None:
            obj = object.__new__(typ, *args, **kwargs)
            OnlyOne.__instance = obj
            
        return OnlyOne.__instance

print OnlyOne() == OnlyOne()

# testing derived class

class My1(OnlyOne): pass 

print My1() == My1()

4 comments

thanos vassilakis 16 years, 11 months ago  # | flag

Is this just noise? The solution is okay, but I've seen hundreds of these, and some exactly the same. This entry looks like noise in an attempt to ... ... maybe create presence ? Is the submitter planning a patent application. He won't be the first.

David Fung 16 years, 11 months ago  # | flag
    if OnlyOne.__instance == None:

        obj = object.__new__(typ, *args, **kwargs)

        OnlyOne.__instance = obj

looks like we need to make this three lines atomic...

anurag uniyal (author) 16 years, 6 months ago  # | flag

My porpose in neither to generate noise nor presence... i just wanted to know how is the solution and which one i use if i need signleton?

Created by anurag uniyal on Thu, 10 May 2007 (PSF)
Python recipes (4591)
anurag uniyal's recipes (12)

Required Modules

  • (none specified)

Other Information and Tasks