On 2006-04-13, [EMAIL PROTECTED] <[EMAIL PROTECTED]> 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. -- http://mail.python.org/mailman/listinfo/python-list