class initialization problem

OKB (not okblacke) brenNOSPAMbarn at NObrenSPAMbarn.net
Fri Sep 18 01:24:27 EDT 2009


rantingrick wrote:

> ok here is some code. this will cause an infinite recursion.
> 
> class A():
>     def __init__(self, *args):
>         self.nestedA = A(*args) #NO GOOD!
> 
> there must be a way to create an instance of an object within the
> same objects constructor?

    	This is an inherent problem with what you want to do, not a problem 
with Python.  You have said you want each instance of A to have a nested 
instance.  But then the nested instance is an instance of A too, so it 
should have a nested instance, and that doubly-nested instance should 
have its own nested instance, and so on to infinity.

    	Perhaps you want to cut off the recursion at the first step, so 
that the nested instance itself does not have a nested instance.  If so, 
add another parameter to __init__ that flags whether you are creating a 
"top-level" instance.

-- 
--OKB (not okblacke)
Brendan Barnwell
"Do not follow where the path may lead.  Go, instead, where there is
no path, and leave a trail."
	--author unknown



More information about the Python-list mailing list