Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #97202
| From | jmp <jeanmichel@sequans.com> |
|---|---|
| Subject | Re: Question re class variable |
| Date | 2015-09-29 13:02 +0200 |
| References | <3948d9cd-24b1-4a3b-8ed0-46bb60a8d738@googlegroups.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.233.1443524549.28679.python-list@python.org> (permalink) |
On 09/29/2015 11:27 AM, plewto@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
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
Question re class variable plewto@gmail.com - 2015-09-29 02:27 -0700
Re: Question re class variable alister <alister.nospam.ware@ntlworld.com> - 2015-09-29 10:00 +0000
Re: Question re class variable John Gordon <gordon@panix.com> - 2015-09-29 14:44 +0000
Re: Question re class variable Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2015-09-29 20:41 -0400
Re: Question re class variable Antoon Pardon <antoon.pardon@rece.vub.ac.be> - 2015-09-29 12:40 +0200
Re: Question re class variable Anssi Saari <as@sci.fi> - 2015-09-29 14:17 +0300
Re: Question re class variable Antoon Pardon <antoon.pardon@rece.vub.ac.be> - 2015-09-29 14:02 +0200
Re: Question re class variable Steven D'Aprano <steve@pearwood.info> - 2015-09-29 22:06 +1000
Re: Question re class variable Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2015-09-29 08:21 -0400
Re: Question re class variable jmp <jeanmichel@sequans.com> - 2015-09-29 13:02 +0200
Re: Question re class variable jmp <jeanmichel@sequans.com> - 2015-09-29 13:11 +0200
csiph-web