Python-Ref > Object oriented programming > Basics > Self
 
 

<-^^->
Klíčová slova
Moduly
Knihovní funkce

Self

How an object refers to itself
When an object accesses its own attributes or methods it does so by using "self" as the name of the object variable. "Self" is also required as the first argument of every method but is not given when the method is called. It is instead supplied automatically by Python based on the object preceding "." in the method call.
Expand/Shrink
Zdroj: (oop3-1.py)
  1   class Apple:
  2     """class apple"""
  3   
  4     def __init__( self, color, weight):
  5       self.color = color
  6       self.weight = weight
  7   
  8     def show( self):
  9       print "%s apple weighting %s" % (self.color, self.weight)
 10   
 11     def print_self( self):
 12       print self
 13   
 14     def method3( self, x, y, z):
 15       """this method takes 3 arguments + self"""
 16       pass  # just do nothing
 17   
 18   a = Apple( "red", "100g")
 19   # the three following are the same
 20   print a
 21   a.print_self()
 22   Apple.print_self( a)
 23   # now see what the number of arguments in the error message is
 24   a.method3( 1)
 25   
 26     
stdout:
<__main__.Apple instance at 0x2b89e500ff38>
<__main__.Apple instance at 0x2b89e500ff38>
<__main__.Apple instance at 0x2b89e500ff38>
stderr:
Traceback (most recent call last):
  File "oop3-1.py", line 24, in ?
    a.method3( 1)
TypeError: method3() takes exactly 4 arguments (2 given)
Doba běhu: 21.1 ms