[Tutor] understanding classes

Magnus Lycka magnus@thinkware.se
Wed, 14 Aug 2002 03:40:59 +0200


At 23:15 2002-08-13 +0200, Gregor Lingl wrote:
>Lance E Sloan schrieb:
>>I have one question:  As far as you know, is "self" in Python basically=20
>>the same as "this" in Java?
>As far as I understand it, YES.

The main difference is the Python principle that
"Explicit is better than Implicit". Thus there
is no implied use of members in classes. You always
need to state "self.x" explicitly. In C++ (and I
guess in Java) you only need to type "this.x" if
there is a local variable "x" which "hides" this.x.
In python an unqualified "x" will always be a local
or global variable, never an instance or class member.

Imagine:

class X:
     def y(self, value):
         print value
x =3D X()

x.y(5) is basically a compact way of writing X.y(x, 5).

There is a slight ambiguity with self and class attributes
though.

 >>> class X:
...     x =3D 5
...     def show(self):
...             print self.x
...
 >>> a =3D X()
 >>> a.show()
5
 >>> a.x =3D 7
 >>> a.show()
7
 >>> X.x
5
 >>> X.x =3D 4
 >>> a.show()
7
 >>> b =3D X()
 >>> b.show()
4
 >>> X.x =3D 5
 >>> b.show()
5
 >>> b.x =3D 'Hello'
 >>> b.show()
Hello

In other words, self.x inside a method (or a direct
attribute access like "a.x") will show the value of
a class attribute with the same name if there is no
instance attribute, but if there is an instance attribute,
the class attribute is hidden, because self.x will
now refer to something else. This is a little similar
to local x hiding this.x in C++/Java.

It can be accessed if you explicitly look for it with
"X.x", but if you use inheritance, it might not be
clear in what context the variable is defined. No
problem if the class attribute is considered read-only,
but if you communicate between instances belonging to
different classes in a class hierarchy by changing
class attributes, you might certainly mess things up.




--=20
Magnus Lyck=E5, Thinkware AB
=C4lvans v=E4g 99, SE-907 50 UME=C5
tel: 070-582 80 65, fax: 070-612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se