What is self.file = file for?

Gary Herron gherron at islandtraining.com
Tue May 13 18:25:16 EDT 2008


wxPythoner at gmail.com wrote:
> Hello!
>
> I have trouble understanding something in this code snippet:
>
> class TextReader:
>     """Print and number lines in a text file."""
>     def __init__(self, file):
>         self.file = file
>         .
>         .
>         .
>
>
> When would you do a thing like  self.file = file  ? I really don't
> find an answer on this. Please help me understand this.
> --
> http://mail.python.org/mailman/listinfo/python-list
>   

If you know about Object-Oriented Programming this should make sense.  
If you don't, then you have some reading/learning to do first.

When someone wants to create an object of type TextReader, they must 
supply a value
   ob = TextReader(v)
That calls the __init__ constructor with the supplied value of v in the 
variable named file.
If the object being created wants to record the value for future use, 
then the line
  self.file = file
does just that.   "self" is the name of the object being created, 
"self.file" is an attribute named "file" of that object, and the 
assignment stores the supplied value there.

Gary Herron





More information about the Python-list mailing list