[Tutor] Getting at object names

Bob Gailer bgailer@alum.rpi.edu
Tue Apr 1 11:48:01 2003


--=======1A7D2F32=======
Content-Type: text/plain; x-avg-checked=avg-ok-F9A4B05; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit

At 05:40 PM 4/1/2003 +0200, Charlie Clark wrote:
>friday = []
>saturday = []
>sunday = []
>
>days = {'1': friday, '2': saturday, '3': sunday}
>
># the lists are then filled
>
>d = days.keys

Should be d = days.keys()

>d.sort

Should be d.sort()

>for day in d:
>         print days[day].__name__, days[day],

Are you wanting the output to look like: friday [1, 2, 3] saturday [6] 
sunday [4, 5]?

That can't be done easily the way you've structured things. The lists don't 
have names. What's in the dictionary are references to the lists, and the 
variables friday, sturday and sunday are also references to the lists. You 
could get at the variable names by searching thru globals() and comparing 
ids, but that's messy.

OOP to the rescue!

#subclass list and give it a name attribute:
class day(list):
   def __init__(self, name):
     self.name = name
   def set(self, items):
     self[:] = items

# create the list objects and give them names
friday = day('friday')
saturday = day('saturday')
sunday = day('sunday')

# fill the lists
friday.set([1,2,3])
saturday.set([4,5])
sunday.set([6])

days = {'1': friday, '2': saturday, '3': sunday}
d = days.keys()
d.sort()
for day in d:
   print days[day].name, days[day],

Note there are many other ways to fill the lists besides my set() method.

Bob Gailer
PLEASE NOTE NEW EMAIL ADDRESS bgailer@alum.rpi.edu
303 442 2625

--=======1A7D2F32=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-F9A4B05
Content-Disposition: inline


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.463 / Virus Database: 262 - Release Date: 3/17/2003

--=======1A7D2F32=======--