On Wed, 20 Apr 2005 08:33:48 -0400, Kent Johnson <[EMAIL PROTECTED]> wrote:

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

Reply via email to