understaning "self"

Poppy znfmail-pythonlang at yahoo.com
Thu Feb 21 12:32:22 EST 2008


Thanks for your explanation and pointer.

"Mike Driscoll" <kyosohma at gmail.com> wrote in message 
news:e057baaa-44e2-483c-a25a-5a544d8edd05 at p43g2000hsc.googlegroups.com...
> On Feb 21, 7:34 am, "Poppy" <znfmail-pythonl... at yahoo.com> wrote:
>> I've been searching online to try get a better understanding of what 
>> "self"
>> does when I define this parameter in my class functions. All I'm finding 
>> is
>> debates on whether  "self" has any value to the language but that doesn't
>> help me in my newbie question. So the code excerpt below is from 
>> "Beginning
>> Python" Norton, Samuel, Aitel, Foster-Johnson, Richardson, Diamon, 
>> Parker,
>> and Roberts.
>>
>> What I think "self" is doing is limiting the function call to only 
>> function
>> in "this" class. So in the function below "has" calls self.has_various(), 
>> if
>> I had a function called "has_various" in my program or another included
>> class using "self" insures that the "has_various" below is the one used. 
>> Am
>> I correct in my understanding?
>>
>> thanks,
>>
>> Zach-
>>
>>     def has(self, food_name, quantity=1):
>>         """
>> has(food_name, [quantity]) - checks if the string food_name is in the
>> fridge. quantity defaults to 1
>> returns True if there is enough, false otherwise.
>> """
>>
>>         return self.has_various({food_name:quantity})
>>
>>     def has_various(self, foods):
>>         """
>> has various(foods) determines if the dictionary food_name
>> has enough of every element to satisfy a request.
>> returns true if there's enough, Fasle if there's not or if an element 
>> does
>> not exist.
>> """
>>         try:
>>             for food in foods.keys():
>>                 if self.items[food] < foods[food]:
>>                     return False
>>             return True
>>         except KeyError:
>>             return False
>
> I think you are correct. The term "self" is a convention more than
> anything. You can use another name, but it's not recommended as 99% of
> developers expect it to be called "self".
>
> You can read up on it here: 
> http://www.diveintopython.org/object_oriented_framework/defining_classes.html
>
> In there, they define it this way and I quote:
>
> "The first argument of every class method, including __init__, is
> always a reference to the current instance of the class. By
> convention, this argument is always named self. In the __init__
> method, self refers to the newly created object; in other class
> methods, it refers to the instance whose method was called. Although
> you need to specify self explicitly when defining the method, you do
> not specify it when calling the method; Python will add it for you
> automatically."
>
> Hope that helps.
>
> Mike 





More information about the Python-list mailing list