Cyclic class definations

Nick Vatamaniuc vatamane at gmail.com
Tue Jul 18 15:10:51 EDT 2006


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.


John Henry wrote:
> 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,




More information about the Python-list mailing list