understanding self

Robert Brewer fumanchu at amor.org
Wed Jul 7 19:24:12 EDT 2004


bruce stockwell wrote:
> Using 'self' in classes seems pretty straight forward. My 
> curiosity is 
> why I have to use it. Shouldn't it be implied? If I create an 
> instance 
> of 'human' called 'bruce' and call the method 'blink' why do 
> I have to 
> pass bruce into the method e.g.
> 
> class human:
> 	...code
> 	def blink(self,times):
> 		for i in range(times):
> 			if self.eye_is_closed:
> 				self.eye_open()
> 				self.eye_close()
> 			else:
> 				self.eye_close()
> 			self.eye_open()
> 	def eye_open(self):
> 		...code
> 	def eye_close(self):
> 		...code
> 			
> 
> bruce = human()
> bruce.blink(5)
> 
> blink is a method of bruce because bruce is an instance of human. 
> Reading this silly code I can understand what is going on if self was 
> not included. Can anyone enlighten me as to why we have self?

One way to say it is that *you* might be able to read the code and
understand what was going on if self were not included, but the
interpreter doesn't. Binding 'self' is just a means of being explicit,
so that *all* local variables follow the same rules.

> by the way..six months of python and I'm 10 times the 
> programmer I was 
> with vb

Same here. :)


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org



More information about the Python-list mailing list