[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Instance vs Class variable oddity

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.