By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
439,931 Members | 1,976 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 439,931 IT Pros & Developers. It's quick & easy.

Python circular class inclusion

P: 10
Suppose I have a class setup like this:

Expand|Select|Wrap|Line Numbers
  1. class Foo:
  2.       Bar b
  3. class Bar:
  4.       Foo f
  5.  
How can I make this work, preferably in one file?
Mar 21 '08 #1
Share this Question
Share on Google+
4 Replies


micmast
100+
P: 144
I presume you mean something like this:

Expand|Select|Wrap|Line Numbers
  1. class Foo():
  2.  
  3.     def __init__(self):
  4.         b = Bar()
  5.         b.hello()
  6.  
  7. class Bar():
  8.  
  9.     def hello(self):
  10.         print "hello"
  11.  
  12. f = Foo()
  13.  
$> 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
Mar 21 '08 #2

P: 43
I presume you mean something like this:

Expand|Select|Wrap|Line Numbers
  1. class Foo():
  2.  
  3.     def __init__(self):
  4.         b = Bar()
  5.         b.hello()
  6.  
  7. class Bar():
  8.  
  9.     def hello(self):
  10.         print "hello"
  11.  
  12. f = Foo()
  13.  
$> 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]But I think he means something like
Expand|Select|Wrap|Line Numbers
  1. class Foo():
  2.     def __init__(self):
  3.         self.b = Bar()
  4.  
  5. class Bar():
  6.     def __init__(self):
  7.         self.f = Foo()
  8.  
  9. f = Foo()
  10.  
A fix would be something like
Expand|Select|Wrap|Line Numbers
  1. class Foo():
  2.     def __init__(self, bar=None):
  3.         self.b = bar
  4.         if bar == None:
  5.             self.b = Bar(self)
  6.  
  7. class Bar():
  8.     def __init__(self, foo=None):
  9.         self.f = foo
  10.         if bar == None:
  11.             self.f = Foo(self)
  12.  
  13. f = Foo()
  14.  
Mar 21 '08 #3

P: 10
yes, sorry, I was thinking java when I wrote that. Thanks!
Mar 21 '08 #4

P: 10
yes, sorry, I was thinking java when I wrote that. Thanks!
Mar 21 '08 #5

Post your reply

Sign in to post your reply or Sign up for a free account.