Style question - defining immutable class data members

Matthew Woodcraft matthew at woodcraft.me.uk
Sun Mar 15 14:26:17 CET 2009


Gary Herron <gherron at islandtraining.com> writes:

> Gary Herron <gherron at islandtraining.com> wrote:
> No, you are still misinterpreting your results.  But you can be forgiven
> because this is quite a subtle point about Python's attribute access.
>
> Here's how it works:
>
> On access, self.count (or self.anything) attempts to find "count" in
> the instance variable "self". If that fails, it attempts to lookup
> "count" in the class. If that fails it attempts to lookup "count" in a
> global context, ...). However, on assignment self.count=... *must*
> necessarily mean the local instance variable -- no defaulting to a
> class variable on assignment.
>
> So ...
>
> With your class C2, the line
>   self.count +=1
> which really translates into
>   self.count = self.count + 1
> has two different actions depending on the pass through the inner loop.
> The first time through (when no instance variable "count" exists), that line
> means
>    <create and assign instance variable "count"> = <class variable count> + 1
> and succeeding passes through (now that self.count is defined) become
>    <instance count> = <instance count> +1
> which is now the same as your class C1
>
> To complete the subtlety, if you were to do
>   self.list = self.list + [i]
> you would see list behaving just as count.  However since,
>    list.append(...)
> is an in-place operation, and not an assignment, the creation of an instance
> variable
> is not provoked, and so all instances continue using the single class
> variable.

It seems clear to me that Maxim understood all this when he asked his
original question (you need to understand this subtlety to know why
the trick he was asking about only works for immutable values).

I wish people on this mailing list|newsgroup would be a little more
ready to assume that people really are asking the question they wrote,
and not the FAQ that sounds most like it.

-M-




More information about the Python-list mailing list