classes

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Pablo

    classes

    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.
    In Java it looks as follows:
    public class DBConnection{
    private static DBConnection instance = null;
    private Conn conn = null; // it is supposed to be object returned be
    pg.connect() method of the PyGreSQL module

    /* a constructor must be private to forbid instantiation of the class */
    private DBConnection(){
    conn = new Conn();
    }

    public static DBConnection getInstance(){
    if(instance == null)
    instance = new DBConnection();
    return instance;
    }
    };

    How can I do the same in Python?
    My main problems are:
    1) how to declare a static field (class field not object field)
    2) how to declare a static method
    3) how to declare a private constructor (is it possible?)

    Can someone help me or point me to some documentation with strong emphasis
    on classes? It would be perfect if that documentation had some comparisons
    with classes in Java or C++.

    Best regards
    Pablo
  • Dan Bishop

    #2
    Re: classes

    "Pablo" <[email protected] main.org> wrote in message news:<pan.2003. 07.19.20.46.33. [email protected] main.org>...[color=blue]
    > 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.[/color]
    ....[snip]...[color=blue]
    > How can I do the same in Python?
    > My main problems are:
    > 1) how to declare a static field (class field not object field)[/color]

    <nitpick>You can't. There are no variable declarations in
    Python.</nitpick> You can use static fields, though.
    [color=blue][color=green][color=darkred]
    >>> class HasStaticField:[/color][/color][/color]
    .... field = 4
    ....[color=blue][color=green][color=darkred]
    >>> HasStaticField. field[/color][/color][/color]
    4
    [color=blue]
    > 2) how to declare a static method[/color]

    class HasStaticMethod :
    def method(arg0, arg1): # note the lack of "self"
    # do something with arg0 and arg1
    method = staticmethod(me thod)
    [color=blue]
    > 3) how to declare a private constructor (is it possible?)[/color]

    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.__ins tance is None:
    # initialization code
    Singleton.__ins tance = self
    else:
    raise SingletonError( )
    def getInstance():
    if Singleton.__ins tance is None:
    Singleton()
    return Singleton.__ins tance
    getInstance = staticmethod(ge tInstance)

    Comment

    • Pablo

      #3
      Re: classes

      [cut][color=blue][color=green]
      >> 2) how to declare a static method[/color]
      >
      > class HasStaticMethod :
      > def method(arg0, arg1): # note the lack of "self"
      > # do something with arg0 and arg1
      > method = staticmethod(me thod)[/color]

      That's not exactly what I wanted.
      I would prefer something like this:
      class StaticMethod:
      __instance = None
      def __init__(self):
      if StaticMethod.__ instance is None:
      StaticMethod.__ instance = self
      else:
      raise Exception("Cons tructor may be invoked only once")
      def getInstance():
      if StaticMethod.__ instance is None:
      StaticMethod.__ instance = StaticMethod()
      return StaticMethod.__ instance

      m = StaticMethod.ge tInstance()
      but Python does not allow to invoke any class method without providing an
      instance of the class object

      I've been thinking about Python classes and modules and found out that it
      is possible in Python to create an object in some module and use a
      reference to it from other modules. In Java it's not possible to create
      any object outside of any class.
      So my problem would be solved if I could create a class which would be
      seen only in its module (something like private class). Then I could
      create an object and simply use it across my application.
      It would behave like a static object since it
      wouldn't be possible to create another object in other modules (since the
      class would be visible only it its module), and it also wouldn't be
      possible to create another object in its module (there is no reason for
      it).

      Is it possible to create a class and forbid its use outside its module?


      Thanks for a usefull reply.
      Pablo

      Comment

      • Steven Taschuk

        #4
        Re: classes

        Quoth Michele Simionato:[color=blue]
        > Steven Taschuk <staschuk@telus planet.net> wrote in message news:<mailman.1 058723911.12956 [email protected] >...[/color]
        [...][color=blue][color=green]
        > > _the_instance = None
        > > class MySingleton(obj ect):
        > > def __new__(self):
        > > global _the_instance
        > > if _the_instance is None:
        > > _the_instance = object.__new__( self)
        > > return _the_instance[/color]
        >
        > Why are you using a global here and not [a class attribute][/color]

        The memory of that thread a little while back about using __del__
        with singletons. If the instance is referenced by a class
        attribute, the cyclic reference prevents the __del__ from being
        used. If the cycle goes through a module attribute, though, the
        zapping of module dicts during shutdown breaks the cycle and lets
        the __del__ run. (Whether all this is true depends on the version
        of Python, I think, but I don't know the details.)

        This might be relevant to the OP, whose example was a singleton
        representing the single database connection used by an entire
        application -- in such a case, __del__ would be a natural place to
        make sure the connection is closed properly.

        I should have explained this bit of trickery. :(

        [...][color=blue][color=green]
        > > Second approach: Use a metaclass. See
        > > <http://aspn.activestat e.com/ASPN/Cookbook/Python/Recipe/102187>[/color]
        >
        >
        > Unfortunately, I see that this recipe is not very recommendable. I have
        > just submitted a fix which seems to work:[/color]
        [...]

        Nice!

        --
        Steven Taschuk Aral: "Confusion to the enemy, boy."
        staschuk@telusp lanet.net Mark: "Turn-about is fair play, sir."
        -- _Mirror Dance_, Lois McMaster Bujold

        Comment

        • Michele Simionato

          #5
          Re: classes

          Steven Taschuk <staschuk@telus planet.net> wrote in message news:<mailman.1 058833821.16631 [email protected] >...[color=blue]
          > Quoth Michele Simionato:[color=green]
          > > Steven Taschuk <staschuk@telus planet.net> wrote in message news:<mailman.1 058723911.12956 [email protected] >...[/color]
          > [...][color=green][color=darkred]
          > > > _the_instance = None
          > > > class MySingleton(obj ect):
          > > > def __new__(self):
          > > > global _the_instance
          > > > if _the_instance is None:
          > > > _the_instance = object.__new__( self)
          > > > return _the_instance[/color]
          > >
          > > Why are you using a global here and not [a class attribute][/color]
          >
          > The memory of that thread a little while back about using __del__
          > with singletons. If the instance is referenced by a class
          > attribute, the cyclic reference prevents the __del__ from being
          > used. If the cycle goes through a module attribute, though, the
          > zapping of module dicts during shutdown breaks the cycle and lets
          > the __del__ run. (Whether all this is true depends on the version
          > of Python, I think, but I don't know the details.)
          >
          > This might be relevant to the OP, whose example was a singleton
          > representing the single database connection used by an entire
          > application -- in such a case, __del__ would be a natural place to
          > make sure the connection is closed properly.
          >
          > I should have explained this bit of trickery. :(
          >[/color]
          Thanks for the explation, I missed that thread.

          Michele

          Comment

          Working...