concept of creating structures in python

Steve Holden steve at holdenweb.com
Fri Dec 12 11:00:38 EST 2008


Joe Strout wrote:
> On Dec 11, 2008, at 10:52 PM, navneet khanna wrote:
> 
>> I want to create a structure within a structure i.e. nested structures
>> in python.
>> I tried with everything but its not working.
>> my code is like this:
>>
>> class L(Structure):
>>
>>     def __init__(self,Name='ND',Addr=0,ds_obj = D()):
> 
> Change the default value of ds_obj here to None.  Otherwise, you will
> certainly confuse yourself (there would be just one default object
> shared among all instances).
> 
>>         self.Name = Name
>>         self.Addr = Addr
>>         self.ds_obj = ds_obj
>>
>>
>> class D(Structure):
>>
>>     def  __init__(self,dataName='ND',index = 0,ele_obj=E()):
>>
>>         self.dataName = dataName
>>         self.index = index
>>         self.ele_obj = ele_obj
> 
> Same thing here with ele_obj -- have it default to None to save yourself
> grief.
> 
> Otherwise, these look fine.
> 
Joe missed a piece out here. If you change the signature of your
D.__init__() to read

     def  __init__(self, dataName='ND', index = 0, ele_obj=None):

then you need to insert the following code at the top of the method:

        if ele_obj is None:
            ele_obj = E()

[You'll note, by the way, I have inserted standard spacing into the
"def" statement to enhance readbility: you should use spaces after all
commas if you want your code to be easy for other programmers to read).
This avoids a common beginner pitfall. Your original code would create a
single E object that would be used as the defauilt for all Ds created
without explicitly passing an ele_obj. Then if that object were changed
(mutated) in some way, all such E's would see a change had been made to
their ele_obj. With the extra code, a different ele_obj is created for
each E that isn't passed one.

The same argument applies to L.__init__()'s ds_obj argument.
> 
>> these are two structures. I want to refer D structure in L one and use
>> it. I want to access the value of D structure like L.D.index = 0.
> 
[...]

regards
 Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC              http://www.holdenweb.com/




More information about the Python-list mailing list