Instance vs Class variable oddity
dieter
dieter at handshake.de
Sat May 18 01:04:59 EDT 2019
Irv Kalb <Irv at furrypants.com> writes:
> ...
> The only thing that threw me was that in a line like:
>
> self.x = self.x + 1
>
> in a method, these two uses of self.x can refer to different variables. I actually teach Python, and this would be a very difficult thing to explain to students.
>
> I have never run across this issue because I would never use the same name as an instance attribute and a class attribute.
I use this regularly.
Think of the "class attribute" as providing a default for
a potential "instance attribute" of the same name.
In Python, almost everything from a class can be overridden
by the instance (exceptions: some special methods, descriptors).
Thus, one can (almost) view a class as a defaults provider for
its instances. Class attributes are just one case.
More information about the Python-list
mailing list