understanding the self in relation to variables

Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: Feb 2009
Posts: 160
Reputation: mahela007 is an unknown quantity at this point 
Solved Threads: 1
mahela007 mahela007 is offline Offline
Junior Poster

understanding the self in relation to variables

 
0
  #1
Sep 5th, 2009
I understand that python provides a value for self when methods are called on the instance of a class.
However, I don't understand how self works when assigning value to a variable of instance.
  1. class snake:
  2. def __init__(self,name):
  3. self.name=name#this is the bit I don't understand. How is self.name #interpreted by python?
Last edited by mahela007; Sep 5th, 2009 at 9:18 am.
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 1,546
Reputation: Ene Uran has a spectacular aura about Ene Uran has a spectacular aura about 
Solved Threads: 174
Ene Uran's Avatar
Ene Uran Ene Uran is offline Offline
Posting Virtuoso

Re: understanding the self in relation to variables

 
1
  #2
Sep 5th, 2009
Look over this code sample, it should be very explanatory:
  1. # role of self in Python classes
  2. # self can be named different, but 'self' is convention
  3.  
  4. class Snake:
  5. def __init__(self, name):
  6. # self keeps track of each instance
  7. # and also makes self.name global to class methods
  8. self.name = name
  9. # test
  10. print(self)
  11.  
  12. def isnice(self):
  13. # a class method has self as the first argument
  14. return self.name + " is very nice"
  15.  
  16. # create 2 instances of class Snake
  17. bob = Snake('Bob Python')
  18. mary = Snake('Mary Rattle')
  19.  
  20. print('-'*40)
  21.  
  22. # now you can get the name that has been assigned to self.name
  23. print(bob.name)
  24. print(mary.name)
  25.  
  26. # access the class method
  27. print(mary.isnice())
  28.  
  29. """my result -->
  30. # self for each instance has a different location in memory
  31. <__main__.Snake object at 0x01E0B2B0>
  32. <__main__.Snake object at 0x01E0B090>
  33. ----------------------------------------
  34. Bob Python
  35. Mary Rattle
  36. Mary Rattle is very nice
  37. """
Last edited by Ene Uran; Sep 5th, 2009 at 11:25 am.
drink her pretty
Reply With Quote Quick reply to this message  
Join Date: Feb 2009
Posts: 160
Reputation: mahela007 is an unknown quantity at this point 
Solved Threads: 1
mahela007 mahela007 is offline Offline
Junior Poster

Re: understanding the self in relation to variables

 
0
  #3
Sep 5th, 2009
thanks!
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:




Views: 349 | Replies: 2
Thread Tools Search this Thread



Tag cloud for Python
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC