trying to grasp OO : newbie Q?

Ben C spamspam at spam.eggs
Thu Apr 13 10:39:04 EDT 2006


On 2006-04-13, mitsura at skynet.be <mitsura at skynet.be> wrote:
> Hi,
>
> I just started with Python and I am new to OO programming.
> Here is a simple code:
> "
> class Obj:
> 	myVar = 1
>
> 	def __init__(self):
> 		myVar = 2
>
> #
>
>
> myObj = Obj()
>
> print myObj.myVar
> "
>
> The output is of this script is '1'. I would except it to be '2'.
> I not understanding something fundamentally here.

Good example, it demonstrates these things quite well.

My understanding of this is as follows:

myVar is a class variable, because you define it in the body of the
class statement (not in any method).

In Python, classes and instances can both be thought of as dictionaries,
i.e. sets of key-value pairs.

In this example, Obj is a class and myObj is an instance.

When you write print myObj.myVar, the interpreter looks first in myObj
for a value matching the key "myVar". It doesn't find one there (I
explain why not below). So it continues the search in myObj's class,
which is the class Obj. It does find one there, with the value 1, so
that's what you get.

The myVar that you define in __init__ is not an instance variable, but a
local variable (local to the function __init__). To make an instance
variable you have to use "self" explicitly:

def __init__(self):
    self.myVar = 2

If you write it like this, your program will print out 2.

People coming from languages like C++ where this-> is implicit sometimes
forget to write "self."; in Python you always need it to get at the
instance.



More information about the Python-list mailing list