understaning "self"

P

Poppy

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
 
M

Mike Driscoll

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
 
P

Poppy

Thanks for your explanation and pointer.

Mike Driscoll said:
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
 
N

Nicola Musatti

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?

I'll try to explain with as simple an example as I can think of. First
of all, 'self' is just a conventional name, it isn't a keyword and has
no special meaning per se. You could just as easily write:

In [10]: class A(object):
....: def __init__(this, n):
....: this.n = n
....:
....: def f(me):
....: print me.n
....:
....:

In [11]: a = A(42)

In [12]: a.f()
42

The point is that when you write a statement such as

a.f()

the interpreter uses 'a' in two ways: first, to find which function
f() to call; second, as a parameter to f() itself. The conventional
'self' helps you remind that the first argument is going to be the
instance of the class on which the function f() is going to be called.

You can actually separate the two uses above with the following
equivalent call:

In [13]: A.f(a)
42

Here you tell the interpreter which function f() to call by specifying
its class, A, and you pass it 'a' explicitly as an argument.

One could argue that the C++/Java/C# approach where you don't specify
the current instance as an argument, but can optionally use the 'this'
keyword to refer to it is more convenient; however the explicit 'self'
makes it possible for free functions and class methods to work in
exactly the same way. This in turn makes the language more consistent
and makes some more advanced, very effective techniques possible.

Hope this helps.

Cheers,
Nicola Musatti
 
7

7stud

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



def bark():
print "Yip, yip."


class Dog(object):
def __init__(the_obj_that_called_this_method):
the_obj_that_called_this_method.name = "Blackie"
print "Initializing a dog object."

def bark(the_obj_that_called_this_method):
print 'My name is', the_obj_that_called_this_method.name
print "Woof, woof."


d = Dog()
d.bark()

Because the variable name: 'the_obj_that_called_this_method' is too
hard to type, by convention people use the variable name: 'self'
instead.
What I think "self" is doing is limiting the function
call to only function in "this" class.

No. Whenever you write obj.method_name, the '.' directs python to
look inside obj's class definition for the specified method. When you
call a function like this:

def show(x):
print x

show('hello')

python assigns the argument 'hello' to the parameter variable x. When
you write:

d.bark()

even though there are no arguments specified in that method call,
python secretly passes one argument to the method: the object on the
left side of the '.'.
 
7

7stud

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?

    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

def bark():
    print "Yip, yip."

class Dog(object):
    def __init__(the_obj_that_called_this_method):
        the_obj_that_called_this_method.name = "Blackie"
        print "Initializing a dog object."

    def bark(the_obj_that_called_this_method):
        print 'My name is', the_obj_that_called_this_method.name
        print "Woof, woof."

d = Dog()
d.bark()

Because the variable name: 'the_obj_that_called_this_method' is too
hard to type, by convention people use the variable name: 'self'
instead.
What I think "self" is doing is limiting the function
call to only function in "this" class.

No.  Whenever you write obj.method_name, the '.' directs python to
look inside obj's class definition for the specified method.  When you
call a function like this:

def show(x):
    print x

show('hello')

python assigns the argument 'hello' to the parameter variable x.  When
you write:

d.bark()

even though there are no arguments specified in that method call,
python secretly passes one argument to the method: the object on the
left side of the '.'.

self is just a parameter variable in a function definition, and just
like any other parameter variable in a function definition, self
stands ready to have any argument passed to the function assigned to
it. It just so happens, that *you* aren't the one specifying the
*first* argument when you call a function in a class. Functions in a
class are called 'methods', and all method calls of the form:

d.bark()

are transformed into this:

d.bark(d)

so bark() in d's class needs to be defined with one parameter
variable--even though the method call looks like bark() should be
defined with no parameter variables. On the other hand, if bark()
were defined like this:


class Dog(object):
def __init__(the_obj_that_called_this_method):
the_obj_that_called_this_method.name = "Blackie"
print "Initializing a dog object."

def bark(the_obj_that_called_this_method, sound):
print 'My name is', the_obj_that_called_this_method.name
print sound


Then you would call bark() like this:

d = Dog()
d.bark('Woof!')

and the call:

d.bark('Woof!')

would be transformed into:

d.bark(d, 'Woof!')

As a result, bark() must be defined with two parameter variables: one
for d and one for the string.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top