static class methods in Python?

Tres Seaver tseaver at starbase.neosoft.com
Sat Feb 19 02:07:54 CET 2000


In article <slrn8arn3d.9md.neelk at brick.cswv.com>,
Neel Krishnaswami <neelk at alum.mit.edu> wrote:
>Gordon McMillan <gmcm at hypernet.com> wrote:
>> Greg Wilson asks:
>> > Have there been any proposals to add the equivalent of "static"
>> > methods (belonging to the class, not to instances) to Python?
>> 
>> The complaints vastly outnumber the proposals.
>> 
>> The most common complaint is the lack of C++ style static 
>> methods. These are usually greeted with hordes of ugly 
>> workarounds. 
>
>This is probably a stupid question, but what /is/ a class method?
>I've never programmed in C++ (or Java), so an explanation would 
>be appreciated. 

It is properly a "static" method in C++, which is declared inside a 
class and which has access to all static data (like class data in Python)
in the class:  public/protected/private.  It can also get to privately
declared things like constructors, and to the private instance data of
instances of its class passed to it as parameters.

One canonical use is to implement the Singleton pattern, e.g.:

  class Unique
  {
    public:

      static
      Unique*    theUnique()
      {
          if( ! s_theUnique )
          {
              s_theUnique = new Unique();
          }
          return s_theUnique;
      }

	  // other methods elided.

    private:

	  Unique();  //implemented out of line

      static
      Unique*    s_theUnique = 0;
  };

Clients of the Unique class will be guaranteed to get the one-and-only instance
of Unique, because they can't get to the constructor, but have to go through
the "singleton" method.

Static methods have traditionally been used as callbacks, because the
interfaces to which the callbacks were passed expected a "real" function,
(normal methods' pointers are of a different type than *function.)  The
canonical callback registration allowed for a pointer-to-function taking a
single void* argument, and for the void* to be passed to it.  A static
method could be passed, because static methods are/were link compatible with
global functions of the same signature (this has morphed recently).

Does-the-FCC-know-about-all-this-static?'ly

Tres.
-- 
---------------------------------------------------------------
Tres Seaver           tseaver at palladion.com       713-523-6582
Palladion Software    http://www.palladion.com



More information about the Python-list mailing list