i don't really understand member variables..
gabor
gabor at realtime.sk
Thu Oct 24 07:03:44 EDT 2002
On Thu, 2002-10-24 at 04:17, Ian Bicking wrote:
> On Wed, 2002-10-23 at 19:54, gabor wrote:
> > hi,
> >
> > until now i thought i understand member variables...
now i understand :-)
thanks to all the people who answered
bye,
gabor
> >
> > but now i don't :-):
> >
> > example:
> > >>> class Test:
> > ... data = []
> > ...
> > >>> a = Test()
> > >>> a.data.append("x")
> > >>> a.data
> > ['x']
> > >>> b = Test()
> > >>> b.data
> > ['x']
> >
> > so they are shared?
> > but now:
> >
> > >>> b.data = ["y"]
> > >>> b.data
> > ['y']
> > >>> a.data
> > ['x']
> >
> > now they aren't anymore....
> >
> > so if i define some data after the class... line then those are
static (
> > as in c++?) but why the stop being static in the second
code-example?
>
> Someone else explained how you start with a class variable. But
there's
> more, as you were able to see...
>
> When you do an assignment like inst.var = something, and the instance
> doesn't already have an instance variable by the name "var", then an
> instance variable is created. So when you did 'b.data = ["y"]', you
> created a "data" instance variable in the b instance (but not in the a
> instance). So when you later say "a.data", it looks in a, finds no
> instance variable, and then looks in Test, and finds a class variable.
> When you do "b.data" it finds an instance variable and returns that,
and
> never looks in Test.
>
> If you want to change the class variable, you'd have to do Test.data =
> ["y"], or perhaps b.__class__.data = ["y"]. But of course if you do
> something like b.data[0] = "y", you will be leaving the list in place,
> and just changing it's 0th member -- so you'd never create an instance
> variable with that statement.
>
> This is all a little contorted. My advice is to simply never assign
to
> class variables -- I usually use them as constants or as state-holding
> objects (i.e., I never reassign the variable, but I might append to a
> list).
>
> Ian
>
>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 196 bytes
Desc: This is a digitally signed message part
URL: <http://mail.python.org/pipermail/python-list/attachments/20021024/a36fb58f/attachment.sig>
More information about the Python-list
mailing list