static class methods and data members

Phil Frost indigo at bitglue.com
Wed Aug 18 18:51:26 EDT 2004


take a look at classmethod and staticmethod with pydoc, in the docs, or
help(). Static data members are done like so:

Class C:
  iAmStatic = 1
  def __init__(self):
    self.iAmNotStatic = 2

Thinking of this in terms of "static" and "automatic" isn't the way to
go, really. That's C's way of doing it, and it's in Java only because
Java is nothing more than C.

Here's how it works: There are classes, and there are instances of those
classes. Each has a namespace. when one does <instance>.name, "name" is
located first in the instance namespace, then in the class namespace.

However, assignment is different. Assignment just looks in the instance
namespace, and if it's not there, it creates it. Thus if one were to do
"self.iAmStatic" in a method of C, that does not change the value of
iAmStatic for all instances of C. However, one can do "C.iAmStatic"
anywhere, and that will change "iAmStatic" for all instances of C that
do not have 'iAmStatic' bound to something at the instance level.

The best way to understand this is through experimentation in the
interactive interpreter. To make things easier, you can peek inside
python's implementation by doing C.__dict__ or anInstanceOfC.__dict__ to
see the dictionary that represents that namespace.

After you have absorbed this, you will probably see the use of
classmethod, as it's not immediately apparent if you aren't familiar with
Python. Happy hacking!

On Wed, Aug 18, 2004 at 02:42:19PM -0700, Neil Zanella wrote:
> Hello,
> 
> I would like to know whether it is possible to define static class methods
> and data members in Python (similar to the way it can be done in C++ or Java).
> These do not seem to be mentioned in "Learning Python" by Mark Lutz and David
> Ascher. It seems like they are a relatively new feature... It seems to me that
> any truly OO programming language should support these so I'm sure that Python
> is no exception, but how can these be defined/implemented in Python? Currently
> I have Python version 2.3 installed on my system.
> 
> Thanks,
> 
> Neil



More information about the Python-list mailing list