Question re class variable
jmp
jeanmichel at sequans.com
Tue Sep 29 07:02:12 EDT 2015
On 09/29/2015 11:27 AM, plewto at gmail.com 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):
self.bar = "I'm an instance attribute"
def foo(self):
print self.bar
print Foo.bar
# this is how you set a class attribute from an instance
Foo.bar = "I am still a class attribute"
print Foo.bar
Foo.foo()
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 self.bar # this is not an assignment so we're fine
Foo.foo()
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:
@property
def id(self):
return id(self) #use the builtin id function
print GameObject().id
Cheers,
JM
More information about the Python-list
mailing list