Could an object delegate itself into another?

Darrell darrell at dorb.com
Thu Oct 21 16:39:59 EDT 1999


Try this search on deja.com

+python +singleton

##########################
class MySingleton:
    def __init__(self):
# Init the singleton
pass

# Instantiate once, overwriting the previous name binding.
MySingleton = MySingleton()

# Try to instantiate it again (this will give an error):
AnotherSingleton = MySingleton()

--
Marc-Andre Lemburg
##########################

http://linux.kreonet.re.kr/python/ftp/www.python.org/workshops/1997-10/proce
edings/savikko.html

#########################
Create a function that returns an instance of the class.  For example:

my_instance = None

def my_factory():
    global my_instance
    if my_instance is None:
        my_instance = MyClass()
    return my_instance

class MyClass:
    ....

Now, you have to make sure that all your users call the function instead of
the class.  One solution would be to rename the class (e.g. give it a '_'
prefix) and give the function the original name of the class.

This doesn't work when you plan to inherit from the class, but I find it
difficult to understand what the singleton pattern should mean when combined
with inheritance anyway -- do you want one instance per class or one total
for the program?

--Guido van Rossum (home page: http://www.python.org/~guido/)
###################################################



--Darrell
----- Original Message -----
From: François Pinard <pinard at iro.umontreal.ca>
To: <python-list at python.org>
Sent: Thursday, October 21, 1999 3:32 PM
Subject: Could an object delegate itself into another?


> Hi, people.  Here I am, with another question.
>
> In one program, I keep a registry of created objects into a dictionary.
> Objects register themselves through their __init__ method.  From outside
> the class, I check if a given object has already been created, so to avoid
> creating another one that would be too similar, kind of redundant.
>
> It would be neat if I could hide this check.  The ideal would be that the
> instantiating call returns an already existing similar object if it
exists,
> instead of a brand new one.  A simple trick is to not instantiate
directly,
> but through some service function that does the check, returning either
> the old object, or a brand new one.
>
> But yet, I wonder.  Could an object really delegates itself into another?
> For example, is there some way by which a newly created object could
> soon check, probably within __init__, if a similar copy has already been
> registered?  If one similar object is found, this newly created object
would
> immediately dismiss itself in favour of the previous one, and the genuine
> class instantiator would return the previous object.  Is that possible?
>
> --
> François Pinard   http://www.iro.umontreal.ca/~pinard
>
> --
> http://www.python.org/mailman/listinfo/python-list





More information about the Python-list mailing list