What is self.file = file for?

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Wed May 14 03:26:54 EDT 2008


afrobeard a écrit :

(top-post corrected. Please, do not top-post).

> On May 14, 3:08 am, wxPytho... 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.
> 
> If you are familiar to C++ or a similar language, the concept of the
> this pointer might not be alien to you. self in this context is
> basically a reference to the class itself.

Nope. It's a reference to the instance.

> Hence self.file is creating
> a class member

Nope. It's setting an instance attribute.

> and setting to the input from file.
> 
> As Gary pointed out, during initialization, only the latter parameter
> i.e. file is being passed to __init__

Nope. Obviously, both parameters are passed - else it just wouldn't 
work. Given an object 'obj' instance of class 'Cls', you can think of 
obj.method(arg) as a convenient shortcut for Cls.method(obj, arg).



More information about the Python-list mailing list