Instance vs Class variable oddity

Irv Kalb Irv at furrypants.com
Fri May 17 14:37:02 EDT 2019


> On May 15, 2019, at 5:41 PM, Ben Finney <ben+python at benfinney.id.au> wrote:
> 
> Irv Kalb <Irv at furrypants.com> writes:
> 
>> I just saw some code that confused me.  The confusion has to do with
>> class variables and instance variables.
> 
> (Perhaps unrelated, but here's another confusion you may be suffering
> from: There's no such thing as a “class variable” or “instance
> variable”. In Python, a “variable” is always a *binding* between a name
> and and object. The “variable” has no concept of different types.)
> 
>> <snip>
> 
> I'm not sure I understand the confusion; once the instance has an
> attribute of that name, the same logic you outlined above applies when
> attempting to resolve that attribute. When ‘self.x’ exists on the
> instance, that's what will be used when resolving ‘self.x’.
> 
> I hope that helps.
> 

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.)

Thanks,

Irv




More information about the Python-list mailing list