Array of objects in Python
Question:
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
Answers:
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()
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())'
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
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()
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())'