Python equivalent of static member data?

Greg Jorgensen gregj at pobox.com
Sat Feb 10 22:39:29 EST 2001


In article <#USeY36kAHA.359 at cpmsnbbsa07>,
  "Roger H" <rhyde99 at email.msn.com> wrote:
> I've just gotten done digging through the docs for 1.5.2,
> and did not find an answer to my question:  Is there a
> Python equivalent to the C++ concept of static member
> data?  I'd like to make a class, and have each instance
> of that class share a variable and its associated value.
> Each instance would have the ability to modify that value,
> and the new value would be updated through all instances.

>From the Python Reference Manual, section 7.6:

Programmer's note: variables defined in the class definition are class
variables; they are shared by all instances. To define instance
variables, they must be given a value in the the __init__() method or
in another method. Both class and instance variables are accessible
through the notation ```codeself.name'', and an instance variable hides
a class variable with the same name when accessed in this way. Class
variables with immutable values can be used as defaults for instance
variables.

You can find this and much more at http://python.org.

If you are used to C++ or Java, Python's syntax for defining class
variables may be a bit confusing. For example, in C++:

  class foo {
      static int x = 33;
      int z;
      ...
  }

x is a class variable, shared by all instances of foo, and z is an
instance variable, unique to each instance of foo. The heavily
overloaded "static" keyword is what makes the difference.

The Python equivalent is:

  class foo:
      x = 33

      def __init__(self):
          self.z = 99

One big difference is that Python will let you easily hide the class
variable behind an instance variable:

>>> foo.x
33
>>> bar = foo()
>>> bar.x
33
>>> bar.z
99
>>> bar.x = 66  # creates a new instance variable for bar
>>> foo.x
33
>>> bar.x
66
>>> bar.__class__.x  # refer to class variable through instance
33
>>> del bar.x
>>> bar.x
33


There's a thread going on about the built-in name None that discusses
scopes and name hiding at greater length.

--
Greg Jorgensen
Portland, Oregon, USA
gregj at pobox.com


Sent via Deja.com
http://www.deja.com/



More information about the Python-list mailing list