Create static method dynamically

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

    Create static method dynamically

    Hello,

    Here is my problem :

    class myClass:
    def addmethod(name, method):
    maClasse.__dict __[name] = method
    addmethod = staticmethod(ad dmethod)

    def hello():
    print "hello"

    myClasse.addmet hod('hello',hel lo)


    Traceback (most recent call last):
    File "<pyshell#0 >", line 1, in -toplevel-
    myClass.hello()
    TypeError: unbound method hello() must be called with myClass instance
    as first argument (got nothing instead)

    I would like to make this call:
    myClass.hello()

    Is there a way of making 'hello' a
    static method of 'myClass ?

    Regards

  • Peter Otten

    #2
    Re: Create static method dynamically

    Salvatore wrote:
    [color=blue]
    > def hello():
    > print "hello"[/color]
    [color=blue]
    > Is there a way of making 'hello' a
    > static method of 'myClass ?[/color]
    [color=blue][color=green][color=darkred]
    >>> class Test:[/color][/color][/color]
    .... def addStaticMethod (name, func):
    .... setattr(Test, name, staticmethod(fu nc))
    .... addStaticMethod = staticmethod(ad dStaticMethod)
    ....[color=blue][color=green][color=darkred]
    >>> def hello(): print "hello"[/color][/color][/color]
    ....[color=blue][color=green][color=darkred]
    >>> t = Test()
    >>> t.addStaticMeth od("hello", hello)
    >>> t.hello()[/color][/color][/color]
    hello[color=blue][color=green][color=darkred]
    >>>[/color][/color][/color]

    Even simpler, if you know the method name beforehand:
    [color=blue][color=green][color=darkred]
    >>> Test.world = staticmethod(he llo)
    >>> t.world()[/color][/color][/color]
    hello

    Peter

    Comment

    • Salvatore

      #3
      Re: Create static method dynamically

      As I always say, the beauty is in the simplicity :-)
      Thank you very much Peter

      Regards

      Salvatore



      Comment

      • Leif K-Brooks

        #4
        Re: Create static method dynamically

        Salvatore wrote:[color=blue]
        > class myClass:
        > def addmethod(name, method):
        > maClasse.__dict __[name] = method
        > addmethod = staticmethod(ad dmethod)
        >
        > def hello():
        > print "hello"
        >
        > myClasse.addmet hod('hello',hel lo)[/color]
        <snip>[color=blue]
        > I would like to make this call:
        > myClass.hello()[/color]

        Change line 3 to:
        myClass.__dict_ _[name] = staticmethod(me thod)

        Comment

        • Salvatore

          #5
          Re: Create static method dynamically

          Leif K-Brooks wrote:[color=blue]
          >
          > Change line 3 to:
          > myClass.__dict_ _[name] = staticmethod(me thod)[/color]

          That make me feel not very proud ;-)
          Thans Leif

          Comment

          Working...