[Tutor] question on self

Steve Willoughby steve at alchemy.com
Mon Mar 12 04:14:37 CET 2012


On 11-Mar-12 20:03, Steven D'Aprano wrote:
> On Sun, Mar 11, 2012 at 07:02:11PM -0700, Michael Lewis wrote:
>> Why do I have to use "self.example" when calling a method inside a class?
>>
>> For example:
>>
>>      def Play(self):
>>          '''find scores, reports winners'''
>>          self.scores = []
>>          for player in range(self.players):
>>              print
>>              print 'Player', player + 1
>>              self.scores.append(self.TakeTurns())
>>
>> I have another method called take turns (not shown for brevity purposes).
>> When I want to call it, why can't I just call it like a function and use
>> TakeTurns() instead of self.TakeTurns()?

Steven's notes about scoping rules are one reason.  Another is the 
matter of object instance binding.  When you call a method, you're not 
just calling a regular function.  You're calling a function bound to a 
particular object, so by saying self.TakeTurns(), Python knows that the 
object "self" is invoking that method, not some other instance of the 
Play class.  That method then can access all of that specific object's 
attributes as necessary.

-- 
Steve Willoughby / steve at alchemy.com
"A ship in harbor is safe, but that is not what ships are built for."
PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C


More information about the Tutor mailing list