Python instances

Bengt Richter bokr at oz.net
Thu Apr 21 05:54:27 EDT 2005


On Wed, 20 Apr 2005 08:33:48 -0400, Kent Johnson <kent37 at tds.net> wrote:

>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)
>

The following shows nothing static anywhere, yet a class has been defined, an instance created, and
__init__ called with initial value, and the value retrieved as an attribute of the returned instance,
and it's all an expression.

 >>> type('C', (), {'__init__': lambda self,v:setattr(self,'foo',v)})('hello').foo
 'hello'

Regards,
Bengt Richter



More information about the Python-list mailing list