Python instances

Kent Johnson kent37 at tds.net
Wed Apr 20 08:33:48 EDT 2005


henrikpierrou at hotmail.com wrote:
> Guess i shouldn't think of the __init__(self) function as a constructor
> then.

No, that's not it. You shouldn't think of variables defined outside of a method as instance variables.

In Java for example you can write something like

public class MyClass {
     private List list = new ArrayList();

     public void add(Object x) {
         list.add(x);
     }
}

In this case list is a member variable of MyClass instances; 'this' is implicit in Java.

In Python, if you write something that looks similar, the meaning is different:

class MyClass:
     list = []

     def add(self, x):
         self.list.append(x)

In this case, list is an attribute of the class. The Java equivalent is a static attribute. In 
Python, instance attributes have to be explicitly specified using 'self'. So instance attributes 
have to be bound in an instance method (where 'self' is available):

class MyClass:
     def __init__(self):
         self.list = []

     def add(self, x):
         self.list.append(x)

Kent



More information about the Python-list mailing list