Python's equivalent of static member data?

Bjorn Pettersen BPettersen at NAREX.com
Thu May 8 06:16:23 EDT 2003


> From: Bram Stolk [mailto:bram at nospam.sara.nl] 
> 
> Hello,
> 
> In C++, you can have static member data: only one instance of 
> the data, shared by all instances of the class.
> 
> What is the equivalent in Python?

Do you want them shared by instances of subclasses also, or just the
class itself?

The simplest way is:

  class Foo(object):
      classVar = 5

      def add(self, n):
          Foo.classVar += n

  f1 = Foo()
  f2 = Foo()
  f1.add(5)
  f2.add(10)
  print Foo.classVar

-- bjorn






More information about the Python-list mailing list