[Tutor] Objects in List

Terry Carroll carroll at tjc.com
Tue May 17 00:34:56 CEST 2005


On Mon, 16 May 2005, Viljoen, Danie wrote:

> My Code:
> 
> class MyObject:        
> 	"""A simple VO class"""
> 	def setName(self, newName):
> 		self.name=newName
> 		
> 	def getName(self):
> 		return self.name
> 
> def main():
> 	list=[]
> 	#created object in container
> 	for i in range(10):
>     		myObject = MyObject()           
>     		name = 'name:' + str(i)
>     		myObject.setName(name)
>     		list.append(myObject)
>     	
>     #manipulate object in list
> 	for p in enumerate(range(10)):
> 		myObject=p
>     		print myObject.getName()

I think what you're looking to do in this second loop is go through the 
list (of instances of MyObject) and print each instance's name.  But your 
for loop doesn't reference list.

(note: "list" is a defined word in Python, so it's best to use something 
else.  I'll use "ObjectList" below, with conforming changes made to the 
earlier loop creating it, of course)

    #manipulate object in list
        for p in ObjectList:
                myObject=p
                print myObject.getName()

Prints:

name:0
name:1
name:2
name:3
name:4
name:5
name:6
name:7
name:8
name:9



> C:\development\python__>python list.py
> Traceback (most recent call last):
>   File "list.py", line 25, in ?
>     main()
>   File "list.py", line 21, in main
>     print myObject.getName()
> AttributeError: 'tuple' object has no attribute 'getName'

Yeah, here's the breakdown of why this is occurring:

>     #manipulate object in list
>       for p in enumerate(range(10)):

This is going to essentially generate feed the for loop with a series of
tuples, with the values (0,0), (1,1)  ... (9,9)  [see Danny's message] .  
Each iteration of teh for loop will use one tuple as the value for p.

>               myObject=p

Now, you've set the label mObject to point to a tuple, e.g., (0,0).

>               print myObject.getName()

Now, you've asked to execute a method named getName in the tuple (0,0).  
A tuple doesn't have that method, so the call failes:

> AttributeError: 'tuple' object has no attribute 'getName'

By the way, normally, you wouldn't use getters and setters in Python in 
the way they dominate in Java.  Instead, you'd just use an 
appropriately named attribute.  It makes for simpler code later.  Here'a a 
more pythonic approach:

class MyObject:
        """A simple VO class"""

def main():
        ObjectList=[]
        #created object in container
        for i in range(10):
                myObject = MyObject()
                myObject.name = 'name:' + str(i)
                ObjectList.append(myObject)

    #manipulate object in list
        for p in ObjectList:
                print p.name

if __name__ == '__main__':
        main()





More information about the Tutor mailing list