How to approach this?

Alex cut_me_out at hotmail.com
Sun Jul 9 17:03:04 EDT 2000


> I want there to be just one instance of the database class which is
> created as soon as it's needed by a dependant class.

This might be worth a try.

Alex.

class Connection:

    '''Replace this with whatever actually makes the connection'''
    
    def query(self, query):
        print query

class Connection_wrapper:

    '''Dependant classes should call this.'''

    connection = None
    reference_count = 0

    def __init__(self):
        ref_cnt = Connection_wrapper.reference_count
        Connection_wrapper.reference_count = ref_cnt + 1
        if Connection_wrapper.connection == None:
            Connection_wrapper.connection = Connection()

    def __getattr__(self, attr):
        return getattr(self.connection, attr)

    def __del__(self):

        # Can't refer to the class as Connection_wrapper, that name
        # can get overwritten by another version of the class during
        # repeated interactive invocations, for instance.        
        my_class = self.__class__
        ref_cnt = my_class.reference_count
        my_class.reference_count = ref_cnt - 1
        if my_class.reference_count == 0:
            my_class.connection = None

class Dependant_class:

    def __init__(self):
        self.connection = Connection_wrapper()

    def query(self, query):
        self.connection.query(query)

t = Dependant_class()
t.query('Testing that the query method gets called.')
t.connection.connection.touched_p = 'touched.'

s = Dependant_class()
connection = s.connection.connection
assert hasattr(connection, 'touched_p') and \
       (connection.touched_p == 'touched.'), \
       'Should be the same instance.'



More information about the Python-list mailing list