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 / [email protected]
"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
_______________________________________________
Tutor maillist  -  [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to