Classes referencing each other

Ryan Ginstrom ginstrom at tree.odn.ne.jp
Mon Nov 6 10:39:37 CET 2006


> Behalf Of Manuel Bleichner
> In a module I have a huge number of classes of the form:
> 
> class A(object):
>    connected_to = [B, C]
>    <other attributes...>
> 
> class B(object)
>    connected_to = [C]
>    <other attributes...>
> 
> class C(object)
>    connected_to = [A]
>    <other attributes...>
> 
> As you see, classes A and B reference classes that are not 
> yet defined when the class is being defined.
> It will raise a NameError: 'B'.

How about a connection broker?

Simple example:

#############################
connections = {}

def Register( obj ):
	try:
		connections[obj.name]['obj'] = obj
	except KeyError:
		connections[obj.name] = { 'obj' : obj, 'connected_to' : [] }

def ConnectTo( objname, obj ):
	try:
		connections[objname]['connected_to'].append( obj )
	except KeyError:
		connections[objname] = { 'obj' : None, 'connected_to' :
[obj] }

class ConnectionObject:
	def __str__(self):
		return self.name

class A(ConnectionObject):
    def __init__(self):
        self.name = 'A'
        Register( self )
        ConnectTo( 'B', self )


class B(ConnectionObject):
    def __init__(self):
        self.name = 'B'
        Register( self )
        ConnectTo( 'A', self )
        ConnectTo( 'C', self )


class C(ConnectionObject):
    def __init__(self):
        self.name = 'C'
        Register( self )
        ConnectTo( 'A', self )


a = A()
b = B()
c = C()


for (key, val) in connections.iteritems():
    print 'object: %s (%s)' % ( key, val['obj'] )
    str_vals = []
    for obj in val['connected_to']:
        str_vals.append( str( obj ) )
    print '\tconnections from:', str_vals

#############################
Output:

object: A (A)
	connections from: ['B', 'C']
object: C (C)
	connections from: ['B']
object: B (B)
	connections from: ['A']
object: D (None)
	connections from: ['C']

Regards,
Ryan Ginstrom




More information about the Python-list mailing list