Python circular class inclusion

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • thegeneralguy
    New Member
    • Aug 2007
    • 10

    Python circular class inclusion

    Suppose I have a class setup like this:

    Code:
    class Foo:
          Bar b
    class Bar:
          Foo f
    How can I make this work, preferably in one file?
  • micmast
    New Member
    • Mar 2008
    • 144

    #2
    I presume you mean something like this:

    Code:
    class Foo():
    	
    	def __init__(self):
    		b = Bar()
    		b.hello()
    
    class Bar():
    	
    	def hello(self):
    		print "hello"
    
    f = Foo()
    $> python test.py
    hello

    To others, how do you create those python code blocks? I have been trying but I cannot figure it out :s

    Comment

    • elcron
      New Member
      • Sep 2007
      • 43

      #3
      Originally posted by micmast
      I presume you mean something like this:

      Code:
      class Foo():
      	
      	def __init__(self):
      		b = Bar()
      		b.hello()
      
      class Bar():
      	
      	def hello(self):
      		print "hello"
      
      f = Foo()
      $> python test.py
      hello

      To others, how do you create those python code blocks? I have been trying but I cannot figure it out :s
      Just start the block with [code=python][code=python][/code]

      But I think he means something like
      [CODE=python]
      class Foo():
      def __init__(self):
      self.b = Bar()

      class Bar():
      def __init__(self):
      self.f = Foo()

      f = Foo()
      [/CODE]
      A fix would be something like
      [CODE=python]
      class Foo():
      def __init__(self, bar=None):
      self.b = bar
      if bar == None:
      self.b = Bar(self)

      class Bar():
      def __init__(self, foo=None):
      self.f = foo
      if bar == None:
      self.f = Foo(self)

      f = Foo()
      [/CODE]

      Comment

      • thegeneralguy
        New Member
        • Aug 2007
        • 10

        #4
        yes, sorry, I was thinking java when I wrote that. Thanks!

        Comment

        • thegeneralguy
          New Member
          • Aug 2007
          • 10

          #5
          yes, sorry, I was thinking java when I wrote that. Thanks!

          Comment

          Working...