classes

Dan Bishop danb_83 at yahoo.com
Sat Jul 19 22:26:08 EDT 2003


"Pablo" <pablo at bogus.domain.org> wrote in message news:<pan.2003.07.19.20.46.33.864915 at bogus.domain.org>...
> Hello everyone
> 
> I have a problem with classes and hope someone can help me.
> I'm used to Java and want to make a singleton class which would allow to
> create only one instance of the class.
...[snip]...
> How can I do the same in Python?
> My main problems are:
> 1) how to declare a static field (class field not object field)

<nitpick>You can't.  There are no variable declarations in
Python.</nitpick>  You can use static fields, though.

>>> class HasStaticField:
...    field = 4
...
>>> HasStaticField.field
4

> 2) how to declare a static method

    class HasStaticMethod:
       def method(arg0, arg1):  # note the lack of "self"
          # do something with arg0 and arg1
       method = staticmethod(method)

> 3) how to declare a private constructor (is it possible?)

It's not possible (afaik) to define a private constructor.  But it is
possible to enforce that a constructor can be called only once.

    class SingletonError(Exception):
       pass

    class Singleton:
       __instance = None
       def __init__(self):
          if Singleton.__instance is None:
             # initialization code
             Singleton.__instance = self
          else:
             raise SingletonError()
       def getInstance():
          if Singleton.__instance is None:
             Singleton()
          return Singleton.__instance
       getInstance = staticmethod(getInstance)




More information about the Python-list mailing list