How to approach this?

Dale Strickland-Clark dale at out-think.NOSPAMco.uk
Tue Jul 11 03:10:35 EDT 2000


Thanks for the replies. I studied them carefully and had a think and I've
come up with this, which I think does what I want:

------------------
class master:
    def __init__(self):
        print "master"

    def __del__(self):
        print "deleted"

    def newslave(self, id):
        return sub(self, id)

class slave:
    def __init__(self, parent, id):
        print "slave init", id
        self.p, id = parent, id

    def __del__(self):
        print "slave del", self.id
-----------------------

'newslave,' being a method of 'master', necessarily requires an instance of
'master'. It returns an instance of 'slave'. However that instance won't be
deleted until all of the instances of 'slave' have gone.


--
Dale Strickland-Clark
Out-Think Ltd, UK
Business Technology Consultants


jepler epler <jepler.lnk at lnk.ispi.net> wrote in message
news:slrn8mhp6b.fu4.jepler.lnk at potty.housenet...
> You may be aware of the idiom:
>
> class C: pass
>
> _instance = None
> def SingletonMaker():
> global _instance
> if _instance is None:
> _instance = C()
> return _instance
>
> thus, instead of instantiating C directly, you call SingletonMaker.
>
> However, this doesn't do the other thing you want, which is to collect
> _instance when it has no more users.
>
> Something like the following ought to work:
>
> class UsesSingleton:
> def __init__(self):
> self.instance = SingletonMaker()
>
> def __del__(self):
> if sys.getrefcount(self.instance) == 3:
> # _instance, self.instance, and the arg to
> # sys.getrefcount
> _instance = None
> # When the function ends, the refcount will
> # drop to 0, so self.instance will be collected
> # and the next call to SingletonMaker will
> # make a new one
> # else, there are other references to the instance...
>
> Of course, if someone else stores a reference to the singleton object,
> this won't work..
>
> Jeff





More information about the Python-list mailing list