Keeping track of subclasses and instances?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Oct 11 01:16:35 EDT 2007


On Wed, 10 Oct 2007 21:35:44 -0700, Michele Simionato wrote:

> On Oct 10, 8:17 pm, Karlo Lozovina <_kar... at mosor.net> wrote:
>> Hi,
>>
>> what's the best way to keep track of user-made subclasses, and
>> instances of those subclasses? I just need a pointer in a right
>> direction... thanks.
>>
>> --
>> Karlo Lozovina -- Mosor
> 
> This recipe does what you want, with the intent of providing automatic
> finalization of the instances, but you should be able to tweak it to do
> everything you wish:
> 
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/523007


Well, that answers my earlier question about why you might want to track 
instances. But it seems like an unnecessarily complicated way of doing it.

>From your recipe:

[module deallocating.py]

import logging

class C(object):
    def __init__(self):
        logging.warn('Allocating resource ...')
    def __del__(self):
        logging.warn('De-allocating resource ...')
        print 'THIS IS NEVER REACHED!'

if __name__ == '__main__':
    c = C()


Is there a problem with writing C like this?

class C(object):
    def __init__(self):
        logging.warn('Allocating resource ...')
        self.__log = logging.warn
    def __del__(self):
        self.__log('De-allocating resource ...')
        print 'THIS IS REACHED!'



It works for me. Have I missed something?


-- 
Steven.



More information about the Python-list mailing list