HI,

Here is my code which I am trying to run:

import array

a = []
for i in range(0,10):
a.append(i+2)

class A:
def __init__(self,a):
self.var1=a[0]
self.var2=a[1]

class B:
def __init__(self, a):
self.g1 = a[2]
self.arr = []


cl1 = []
var = A(a)

for j in range (0,10):
cl1.append(var)

print(cl1[9].var2)

cl2 = []
var3 = B(a)
#var3.arrayCreate(cl1)

for f in range(0,3):
cl2.append(var3)

print(cl2[0].arr[0].var1)

Basically what I am trying to do is: I have class A an array of which is a member of class B. Now I also want to have an array of class B and print out the class A member as I tried in the last line. It doesnt seem to print it and I get an error:

Traceback (most recent call last):
File "C:\Mine\python\arrays.py", line 33, in <module>
print(cl2[0].arr[0].var1)
IndexError: list index out of range

I did Python long ago so there might be other better method, but fixing index is really bad option. Use object meta data like length of list et al
here is a sample code illustrating that!

a = ["Juma", "Roza", "Manenge" ,"Mandawa" "Siku ya Gulio Katerero"]
for name in a:
    print name #add whatever you want to be done here like adding in another thing
    
#alternatively
for i in range(0, len(a)):
    print a[i]

Hi Stefano,

I was able to fix my problem. All I had to do was "Not append the object to the array" but to assign it to the array variable.

Thanks for your time. I shall post the corrected code soon.

Thanks,
Harsha

Hi Stefano,

I was able to fix my problem. All I had to do was "Not append the object to the array" but to assign it to the array variable.

Thanks for your time. I shall post the corrected code soon.

Thanks,
Harsha

Enjoy, mark it solved then!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.