2

I want to define an array of objects (my defined class) of the same type in python.

I tried to use an array module:

from array import *
arrayIdentifierName = array("ClassName",[ClassName1,ClassName2,ClassName3])

it says:

TypeError: array() argument 1 must be char, not str

Then I tried to use a list: Using list won't help since I don't see a method in http://docs.python.org/2/tutorial/datastructures.html that can reach each object without removing it from the list (for example: list.pop([i]) or list.remove(x) will remove the object and I need to change one of it's data members and save it).

Any suggestion guys?

Thanks

3
  • 1
    Use indexing, like yourList[i]? Or simple iteration over the list with for... in? Commented Dec 4, 2013 at 18:46
  • you should be using lists, not arrays. In python, you don't need to use arrays unless you really know what you're doing Commented Dec 4, 2013 at 18:49
  • Thanks it works fine with yourList[i] Commented Dec 4, 2013 at 18:51

2 Answers 2

2

U should be using list....
You can access any object using list and do whatever you want to do using its functions.

class test(object):
    def __init__(self,name):
        self.name=name

    def show(self):
        print self.name

ob1=test('object 1')
ob2=test('object 2')

l=[]
l.append(ob1)
l.append(ob2)

l[0].show()
l[1].show()
Sign up to request clarification or add additional context in comments.

Comments

0

This may be useful if you wish to use inheritance.

class y:
    def __init__(self,s):
        self.s=s
    def f2(self):
        return 1 + self.s
   
class w():
    def t(self,n):
        y1 = y(n)
        return [y1]

a = [10,20,30]
j = w()
fn = []
for i in range(3):
        [x] = j.t(a[i])
        fn.append(x)

print(fn[0].f2())
print(fn[1].f2())
print(fn[2].f2())'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.