when and how do you use Self?
Fredrik Lundh
fredrik at pythonware.com
Thu Nov 3 03:50:47 EST 2005
"Tieche Bruce A MSgt USMTM/AFD" <bruce.tieche at usmtm.sppn.af.mil> wrote:
> Could someone explain (in English) how and when to use self?
>
> I have been reading, and haven't found a good example/explanation
consider a class C:
>>> class C:
... def method(self):
... print self
...
>>> C
<class __main__.C at 0x0091D7E0>
you can create unique instances of this class by "calling" the class itself:
>>> a = C()
>>> a
<__main__.C instance at 0x00925FD0>
>>> b = C()
>>> b
<__main__.C instance at 0x00927030>
here, "a" and "b" are two separate objects, that both refer to the same
class object, but are otherwise distinct (the cryptic codes are object
identities).
now, if you call a method on one of those objects, Python will use the
method code from the class, but the method will get a reference to the
instance as its first argument (self).
when you call the method via the "a" object, the method gets a reference
to the "a" object as the first argument:
>>> a.method()
<__main__.C instance at 0x00925FD0>
when you call the method via the "b" object, the method gets a reference
to the "b" object as the first argument:
>>> b.method()
<__main__.C instance at 0x00927030>
the instance object is usually used to store instance-specific variables
(usually known as "attributes" or "members"). an example:
>>> class Counter:
... def __init__(self):
... self.value = 0
... def increment(self):
... self.value = self.value + 1
... return self.value
...
>>> a = Counter()
>>> b = Counter()
>>> a.increment()
1
>>> a.increment()
2
>>> a.increment()
3
>>> b.increment()
1
(the __init__ method is automatically called for each new instance)
you can also access the instance attributes "from the outside":
>>> print a.value
3
>>> print b.value
1
for more on this, see:
http://docs.python.org/tut/node11.html#SECTION0011300000000000000000
</F>
More information about the Python-list
mailing list