[Tutor] assigning types(?) to list elements

Gonçalo Rodrigues op73418@mail.telepac.pt
Mon, 14 Oct 2002 15:00:12 +0100


From: "Joseph Paish" <jpaish@freenet.edmonton.ab.ca>

> i'm not sure what the correct terminology for what i am trying to do is,
so
> i'll just describe it the best i can.
>
> # code follows
>
> file_handle = open ('/path/to/datafile.txt', 'r')
>
> for each_line in file_handle.readlines() :
>         each_line = each_line.rstrip() # strip off carriage return
>         temp1, temp2, temp3, temp4, temp5, temp6 = string.split(each_line)
>
>         # a sample record is : 'abc 123.45 74 98 234.56 345.67'
>
>         # temp1 is a string so it doesn't need any conversion
>         # but i do need to convert the others so i can do calculations
with
>         #    them
>
>         temp2  = float(temp2)
>         temp3  = int(temp3)
>         temp4  = int(temp4)
>         temp5 = float(temp5)
>         temp6 = float(temp6)
>
> # end code
>
> is there an easier way to assign a type to each of the variables so that i
> can do calculations with them.  the way it is now, if i don't do any
> conversion and add a number to any of temp2 thru temp6, i end up with a
> concatenated string.
>
> i guess i am asking if there is another way to make each of the variables
the
> correct type without doing it one variable at a time the way it is now.
>
> there are a lot more than just the six variables i am using for this
example,
> so one line of code for each variable would get very long.
>
> a pointer to documentation would be very helpful so that i can understand
any
> suggestions for doing what i am trying to do.  of course, an example of
the
> correct way to do it wouldn't be turned down :-)
>
> thanks
>
> joe
>

With python 2.2 onward you can use

temp.__class__

to fetch the class of the temp object. It needs 2.2 because I believe that
with 2.1 and earlier builtin types have no __class__ attribute - although I
am not sure, and I have no way to test it.

Hope it helped,
Gonçalo Rodrigues