Static member variables

Aahz Maruch aahz at netcom.com
Tue Jul 11 11:33:26 EDT 2000


In article <8kd766$qi7$1 at zingo.tninet.se>,
Thomas Svensson <thomas_s at ebox.tninet.se> wrote:
>In article <8kahq3$fof$1 at slb0.atl.mindspring.net>, aahz at netcom.com (Aahz
>Maruch) wrote:
>>
>> You can have class variables, but they're not exactly what I'd call
>> "static" and they certainly aren't constant.
>> 
>> class foo:
>>   bar = 2
>>   def __init__(self):
>>     self.baz = 3
>> 
>> f = foo()
>> 
>> f.bar is a class variable; f.baz is an instance variable.  Note that you
>> can run into problems if you're not careful because of the way scoping
>> rules work.
>
>Very logical when I see it now. About trouble, do you mean something
>similar to this:

No, what I mean is more similar to this:

class foo:
  bar = 2
  def __init__(self, bar):
    self.baz = 3
    self.bar = bar

By using self.bar, you're modifying the instance, not the class
variable, and the change will not be visible to other instances.  Do
this instead:

class Foo:
  bar = 2
  def __init__(self, bar):
    self.baz = 3
    Foo.bar = bar
--
                      --- Aahz (Copyright 2000 by aahz at netcom.com)

Androgynous poly kinky vanilla queer het    <*>     http://www.rahul.net/aahz/
Hugs and backrubs -- I break Rule 6

"do you want my self-identities alphabetically, chronologically, or in
random order?"  -- Misha



More information about the Python-list mailing list