Cyclic class definations

J

John Henry

Hi list,

I am trying to understand better Python packaging. This might be a
messed up class hierachy but how would I break this cyclic relatioship?

In file A:

from B import B_Class

Class_A_Main():
def ....
def SomeMethod(self):
res=B_Class(self)

Class_A_SubClass(Class_A_Main):
def ...


In file B:

Class B_Class():
def __init__(self,parent):
...
def SomeMethod(self):
res=C_Class(self)


In file C:

from file A import Class_A_SubClass

Class C_Class(Class_A_SubClass):
def __init__(self, parent):
...


As you can see, the cyclic relationship exists because C_Class is a
sub-class of SubClass which is in turn a sub-class of Class_A_Main and
in one of the methods of Class_A, it has a need to create a C_Class
object.

I tried to merge the files A and C (by placing C_Class behind A_Class)
and have the method in A_Class create C_Class directly but that doesn't
work because Python says C_Class is not defined when it's processing
the A_Class method. May be somebody can tell me how to "forward
declare" a class?

Regards,
 
J

John Henry

I think I got the answer by playing around a bit. It appears you
*don't* need to forward declare things. For example, the following
code works:

class a:
def run(self):
new_a=a_sub()
new_a.print_it()

class a_sub(a):
def print_it(self):
print "Hi"

b=a().run()

Regards,
 
N

Nick Vatamaniuc

John,
Cycles are tricky. Python is an interpreted dynamic language, whatever
object you instantiate in your methods is a different thing than class
hierarchy. Your class hierarchy is fine: ClassA->ClassASubclass->ClassC
and it should work. If it doesn't, create a quick mock example and
post it along with the error.

In general try to model your problem to avoid cycles if possible, I
know sometimes they are un-avoidable, but more often then not, they
are. Python might or might not allow cycles in certain situations
(packages, imports, class hierarchy and during usage i.e. in your
semantics) but regardless, if they make your code hard to understand so
try to not introduce them if possible.

Hope this helps,
Nick V.
 
J

John Henry

Thanks for the note, Nick.

I ended up with cycles as a historical reason. Some code that were
written long time ago did not anticipate that part of it will get
sub-classed.

Thanks again.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,197
Latest member
Sean29G025

Latest Threads

Top