Instances?

Steve Holden sholden at holdenweb.com
Tue Jul 31 16:35:13 EDT 2001


"Angel Asencio" <asencio at mitre.org> wrote in message
news:3B671064.73902FDF at mitre.org...
> Original class:
>
> class Foo:
>     x = []
>     y = []
>
> Code tested on IDLE:
>
> >>> a = classTest.Foo()
> >>> b = classTest.Foo()
> >>> a.x.append(3)
> >>> b.x
> [3]
>
> Then, chenged the class to:
>
> class Foo:
>     def __init__(self):
>         self.x = []
>         self.y = []
>
> And the new result was:
>
> del(a)
> >>> del(b)
> >>> a = classTest.Foo()
> >>> b = classTest.Foo()
> >>> a.x.append(3)
> >>> b.x
> []
> >>> a.x
> [3]
> >>>
>
>  So, does not putting data attributes inside the __init__ would
> make them the equivalent to class variables on smalltalk or
> static variables in Java?
>
Yes, variables bound in the class scope (such as the method names, which are
bound by the def statements) effectively become attributes of the class. The
same is true, of course, of names explicitly placed inside the class scope
from outside by name qualification (e.g. Foo.classvar = 3). The tricky thing
is that self.var will find a class variable var, but if you assign an
instance variable var, that instance no longer sees the class variable var.

Some code uses this to allow the class to establish default values for
certain instance variables, but it's a bit obscure.

regards
 Steve
--
http://www.holdenweb.com/








More information about the Python-list mailing list