[Tutor] beginner question

Steve Willoughby steve at alchemy.com
Tue Nov 1 16:41:23 CET 2011


On 01-Nov-11 08:34, Mayo Adams wrote:
> When writing a simple for loop like so:
>
>       for x in f
>
> where f is the name of a file object, how does Python "know" to interpret
> the variable x as a line of text, rather than,say, an individual
> character in the file? Does it automatically
> treat text files as sequences of lines?

Every object defines what its behavior will be when asked to do 
something.  In this case, file objects know that they are capable of 
iterating over a list of their contents by being used in a "for x in f" 
loop construct.  The file object knows to respond to that by yielding up 
a line from the file for every iteration.

You could, theoretically, write a variation of the file object class 
which iterated over characters, or logical blocks (records of some sort) 
within files, and so forth.

-- 
Steve Willoughby / steve at alchemy.com
"A ship in harbor is safe, but that is not what ships are built for."
PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C


More information about the Tutor mailing list