Python Class Question


Recommended Posts

I am really struggling trying to understand what the following code is doing. in particulare this line, I do not get what it is doing(where it came from)

self.name = name

where is self.name coming from?

below is the code it came from

class Critter(object):

   """A virtual pet"""

   def __init__(self, name):

       print "A new critter has been born!"

       self.name = name



   def __str__(self):

       rep = "Critter object\n"

       rep += "name: " + self.name + "\n"

       return rep



   def __cmp__(self, other):

       if self.name > other.name:

           return 1

       if self.name < other.name:

           return -1

       if self.name == other.name:

           return 0      



   def talk(self):

       print "Hi.  I'm", self.name, "\n"



# main

crit1 = Critter("Poochie")

crit1.talk()



crit2 = Critter("Randolph")

crit2.talk()



print "Printing crit1:"

print crit1



print "Directly accessing crit1.name:"

print crit1.name

Edited by shanenin
Link to post
Share on other sites

Not sure if you mean self.name specifically or self, so I'll hit both.

'self' is the object itself. That is, in

obj.method()

the 'self' parameter inside method() refers to obj. The object is implicitly passed as the first argument to the function, as though the code was

obj.method(obj)

.

self.name is a field (also known as an attribute, slot, property, member variable...) in self. A variable that's attached to the self object. It's created implicitly when a value is assigned to it, in this case in __init__(). (The details are more complicated, but then the details of all variables are more complicated than they appear.)

Link to post
Share on other sites

Object-oriented programming (OOP) requires a bit of a change of perspective.

There's are conceptual models of OOP that can make it easier to understand, but I'm hesistant to describe them because I don't want corrupt you with an incomplete or faulty model. The the OO world is divided into several camps and the divisions run deep. There's frequently friction when members of different camps come together and their mental models clash.

There are many people who never grok object-orientation or reject it.

Link to post
Share on other sites

I am probably saying something really dumb , but here goes:

is the following code just assigning the variable name(self.name) to the value name, or is something more going on.

self.name = name

if that is the case, why can't any variable be used like the following

word = name

Link to post
Share on other sites

I think I might be on to something. the folowing code does not work

class Critter(object):
   def __init__(self,test):
       print 'I am born'
       self.test = test

   def talk(self):
       print 'my name is',test

crit = Critter('poochie')
crit.talk()

but the following does

class Critter(object):
   def __init__(self,test):
       print 'I am born'
       self.test = test

   def talk(self):
       print 'my name is',self.test

crit = Critter('poochie')
crit.talk()

is this to do with the encapsulation? the only way to get the value of test('poochie') available to the talk method is by using self.something. This gets around the encapsulation.

Edited by shanenin
Link to post
Share on other sites
I am probably saying something really dumb

You're not.

is the following code just assigning the variable name(self.name) to the value name, or is something more going on.

self.name = name

It's a simple assignment, just as you've seen before. The difference is that the 'self.name' designates a variable called 'name' that is a member of the object denoted by 'self'. If it helps, you can think of the object as being like an array except that instead of referencing the elements by integers, you use names. 'self.name' is sort of like 'self[0]'.

if that is the case, why can't any variable be used like the following

word = name

<{POST_SNAPBACK}>

More on that below. It's interesting that you asked that though, because in most OOPLs you could in fact use 'word=name'. Python's use of an explicit 'self' parameter is unusual; Modula 3 is the only other language I can think of that uses it. Most languages have a magic variable named 'self' or 'this' that does the same thing but it only has to be used for self-reference or disambiguation.

is this to do with the encapsulation? the only way to get the value of test('poochie') available to the talk method is by using self.something. This gets around the encapsulation.

<{POST_SNAPBACK}>

Right, it's encapsulation in action. The object designated by 'name' is encapulated in the object designated by 'self'. The expression 'self.name' reaches into 'self' to access 'name'.

(This is really a borderline explanation. The nature of encapsulation is one of those conceptual issues I wanted to avoid until you get a feel for it. Even as I wrote the preceding paragraph I thought of models in which that description is invalid.)

Link to post
Share on other sites
can the parameter "poochie" in the following line of code only be passed to the __init__()  constructer?

crit1 = Critter("Poochie")

<{POST_SNAPBACK}>

No. You could add a mutation function to set the name if you wished.

class Critter(object):

   """A virtual pet"""

   def __init__(self):
       print "A new critter has been born!"
       self.name = ""   # No name yet

   def __str__(self):
       rep = "Critter object\n"
       rep += "name: " + self.name + "\n"
       return rep

   def __cmp__(self, other):
       if self.name > other.name:
           return 1
       if self.name < other.name:
           return -1
       if self.name == other.name:
           return 0      

   def rename(self, name):
       self.name = name

   def talk(self):
       print "Hi.  I'm", self.name, "\n"

You could also assign it directly

crit1.name = "Spot"

but you shouldn't do that.

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...