| | |
understanding the self in relation to variables
Please support our Python advertiser: Programming Forums - DaniWeb Sister Site
![]() |
•
•
Join Date: Feb 2009
Posts: 160
Reputation:
Solved Threads: 1
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.
However, I don't understand how self works when assigning value to a variable of instance.
Python Syntax (Toggle Plain Text)
class snake: def __init__(self,name): 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.
Look over this code sample, it should be very explanatory:
python Syntax (Toggle Plain Text)
# role of self in Python classes # self can be named different, but 'self' is convention class Snake: def __init__(self, name): # self keeps track of each instance # and also makes self.name global to class methods self.name = name # test print(self) def isnice(self): # a class method has self as the first argument return self.name + " is very nice" # create 2 instances of class Snake bob = Snake('Bob Python') mary = Snake('Mary Rattle') print('-'*40) # now you can get the name that has been assigned to self.name print(bob.name) print(mary.name) # access the class method print(mary.isnice()) """my result --> # self for each instance has a different location in memory <__main__.Snake object at 0x01E0B2B0> <__main__.Snake object at 0x01E0B090> ---------------------------------------- Bob Python Mary Rattle Mary Rattle is very nice """
Last edited by Ene Uran; Sep 5th, 2009 at 11:25 am.
drink her pretty
![]() |
Other Threads in the Python Forum
- Previous Thread: Building an ISO for Python project
- Next Thread: How to pass an instance of a class as and argument ?
Views: 349 | Replies: 2
| Thread Tools | Search this Thread |
Tag cloud for Python
apache application argv beginner binary calculator character code command compile cursor cx-freeze development dictionaries dictionary dynamic error event examples excel file float format ftp function google gui homework ideas import input java keyboard launcher line linux list lists loop maze microphone mouse movingimageswithpygame newb number numbers obexftp output parsing path permissions phonebook port prime program programming projects py2exe pygame pygtk pyqt pysimplewizard python random recursion recursive refresh return reverse scrolledtext session shebang signal simple sprite ssh string strings table terminal text thread threading time tkinter tlapse trick tuple tutorial ubuntu unicode unit urllib urllib2 valueerror variable verify voip windows wxpython






