Two python class instances have a reference to each other -


i having 2 python classes, let's call them , b. responsible handling receiving , sending of messages of format on network. b responsible interpretation of messages.

now , b instances of classes , b respectively. consider following scenario:

  • a receives message , calls method of b message interpretation
  • b processes message , wants use method of send response

to achieve constructed 2 classes have reference each other. works fine ask if design flaw , should avoided?

for illustration see following minimal code example:

class a:      def set_b(self, b):         self.b = b   class b:      def set_a(self, a):         self.a =   if __name__ == '__main__':      = a()     b = b()      b.set_a(a)     a.set_b(b) 

cpython added cyclic garbage collection versions ago because cyclic dependencies common enough issue. still, might able not create cycle having methods of a call method of b pass self instead of depending on b having reference a.

if stick cycle, make linkage automatic possible. instance:

class b:     def __init__(self, a):         self.a =         a.set_b(self)  = a() b = b(a) # both instances initialized , ready go. 

if forget pass a b, immediate exception.


Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -