Question re class variable

jmp jeanmichel at
Tue Sep 29 13:02:12 CEST 2015

On 09/29/2015 11:27 AM, plewto at wrote:
> I have a perplexing problem with Python 3 class variables.

Your problem is that when assigning values to your class attribute, you 
are actually creating a instance attribute.

class Foo:
   bar = "I'm a class attribute"
   def __init__(self): = "I'm an instance attribute"

   def foo(self):
     # this is how you set a class attribute from an instance = "I am still a class attribute"

I'm an instance attribute
I'm a class attribute
I am still a class attribute

What can be confusing is that assuming you never use the same name for a 
class an instance attribute (that would be bad code), you can access
your class attribute from the instance:

class Foo:
   bar = "I'm a class attribute"
   def foo(self):
     # python will look into the class scope if not found in the instance
     print # this is not an assignment so we're fine
I'm an class attribute

As side note and unrelated topic, your are using name mangling 
(attribute starting with __), are you sure you need it ? You need a 
strong motive to use this feature otherwise you're making things 
difficult for yourself without any benefit.

Finally here's how I'd code your id, to give some idea on alternative ways:

class GameObject:

   def id(self):
     return id(self) #use the builtin id function

print GameObject().id



More information about the Python-list mailing list