osdir.com


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

Instance vs Class variable oddity


On Sat, May 18, 2019 at 4:40 AM Irv Kalb <Irv at furrypants.com> wrote:
>
> Thanks for your comments.  I am very aware of all the other issues that you explained.
>
> 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 also know that "attribute" is the "official" terms, but I've called them instance variables and class variables for so many years (working in other languages), that I use those terms without thinking.)
>

Yes, this is a little unusual. It's a consequence of the
run-time-lookup that defines attributes, as opposed to the
compile-time-lookup that defines most name bindings. For instance:

x = 0
def f():
    print(x)
    x = 1
    print(x)

will raise UnboundLocalError, rather than printing zero followed by
one. But the global and builtin namespaces are looked up completely
dynamically:

class int(int): pass

This will look up the built-in "int" type, create a subclass, and make
that a global.

So this is uncommon, but not unique. Sometimes, if one thing doesn't
exist, you find another - even if it's going to exist a moment later.

ChrisA