Adding method to object

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

    Adding method to object

    Hi!

    How can I add a method to an object.
    This code does not work:

    class Foo:
    def __init__(self):
    self.counter=0

    f=Foo()

    def incr(self):
    self.counter+=1

    f.incr=incr

    f.incr()

    ===> python extend.py
    Traceback (most recent call last):
    File "extend.py" , line 12, in ?
    f.incr()
    TypeError: incr() takes exactly 1 argument (0 given)

  • Gonçalo Rodrigues

    #2
    Re: Adding method to object

    On Wed, 03 Dec 2003 10:44:12 +0100, "Thomas Guettler"
    <guettli@thom as-guettler.de> wrote:
    [color=blue]
    >Hi!
    >
    >How can I add a method to an object.
    >This code does not work:
    >
    >class Foo:
    > def __init__(self):
    > self.counter=0
    >
    >f=Foo()
    >
    >def incr(self):
    > self.counter+=1
    >
    >f.incr=incr
    >
    >f.incr()
    >
    >===> python extend.py
    >Traceback (most recent call last):
    > File "extend.py" , line 12, in ?
    > f.incr()
    >TypeError: incr() takes exactly 1 argument (0 given)[/color]

    You have to call it like

    f.incr(f)

    If you want to leave out the f as arg (call it like an instance
    method) then
    [color=blue][color=green][color=darkred]
    >>> import new
    >>> help(new.instan cemethod)[/color][/color][/color]
    Help on class instancemethod in module __builtin__:

    class instancemethod( object)
    | instancemethod( function, instance, class)
    |
    | Create an instance method object.
    |
    ....

    And

    new.instancemet hod(incr, f, f.__class__)

    Should do the trick.

    With my best regards,
    G. Rodrigues

    Comment

    • Peter Otten

      #3
      Re: Adding method to object

      Thomas Guettler wrote:
      [color=blue]
      > How can I add a method to an object.[/color]

      self is not passed automatically, if you call an instance attribute.
      You can provide a default value instead:
      [color=blue][color=green][color=darkred]
      >>> class Foo:[/color][/color][/color]
      .... def __init__(self):
      .... self.counter = 0
      ....[color=blue][color=green][color=darkred]
      >>> f = Foo()
      >>> def incr(self=f):[/color][/color][/color]
      .... self.counter += 1
      ....[color=blue][color=green][color=darkred]
      >>> f.incr = incr
      >>> f.incr()
      >>> f.counter[/color][/color][/color]
      1[color=blue][color=green][color=darkred]
      >>>[/color][/color][/color]

      If you have more than one instance with the same incr() method, you can wrap
      it into a lambda:
      [color=blue][color=green][color=darkred]
      >>> g = Foo()
      >>> g.incr = lambda self=g: incr(self)
      >>> g.incr()
      >>> g.incr()
      >>> g.counter[/color][/color][/color]
      2

      Peter

      Comment

      • marco

        #4
        Re: Adding method to object

        Is it possible to do the same thing for an attribut, instead of a method ?

        i'd like to wrap an newAttribute to an oldAttribute one :
        example:
        i've got an instance "n" of an "xmlNode" class
        i'd like to use "n.parentNo de" instead of "n.parent" ...


        "Gonçalo Rodrigues" <op73418@mail.t elepac.pt> a écrit dans le message de
        news: 72krsvcpeur8hhu 74s4bhlsq3bf60f u055@4ax.com...[color=blue]
        > On Wed, 03 Dec 2003 10:44:12 +0100, "Thomas Guettler"
        > <guettli@thom as-guettler.de> wrote:
        >[color=green]
        > >Hi!
        > >
        > >How can I add a method to an object.
        > >This code does not work:
        > >
        > >class Foo:
        > > def __init__(self):
        > > self.counter=0
        > >
        > >f=Foo()
        > >
        > >def incr(self):
        > > self.counter+=1
        > >
        > >f.incr=incr
        > >
        > >f.incr()
        > >
        > >===> python extend.py
        > >Traceback (most recent call last):
        > > File "extend.py" , line 12, in ?
        > > f.incr()
        > >TypeError: incr() takes exactly 1 argument (0 given)[/color]
        >
        > You have to call it like
        >
        > f.incr(f)
        >
        > If you want to leave out the f as arg (call it like an instance
        > method) then
        >[color=green][color=darkred]
        > >>> import new
        > >>> help(new.instan cemethod)[/color][/color]
        > Help on class instancemethod in module __builtin__:
        >
        > class instancemethod( object)
        > | instancemethod( function, instance, class)
        > |
        > | Create an instance method object.
        > |
        > ...
        >
        > And
        >
        > new.instancemet hod(incr, f, f.__class__)
        >
        > Should do the trick.
        >
        > With my best regards,
        > G. Rodrigues[/color]


        Comment

        • Sean Ross

          #5
          Re: Adding method to object

          "marco" <marc.lentz@ctr ceal.caisse-epargne.fr> wrote in message
          news:bqkrsb$nf1 $2@s1.read.news .oleane.net...[color=blue]
          > Is it possible to do the same thing for an attribut, instead of a method ?
          >
          > i'd like to wrap an newAttribute to an oldAttribute one :
          > example:
          > i've got an instance "n" of an "xmlNode" class
          > i'd like to use "n.parentNo de" instead of "n.parent" ...[/color]
          [snip]

          # try this ...
          n.parentNode = n.parent

          HTH
          Sean


          Comment

          • marco

            #6
            Re: Adding method to object

            > > Is it possible to do the same thing for an attribut, instead of a method
            ?[color=blue][color=green]
            > >
            > > i'd like to wrap an newAttribute to an oldAttribute one :
            > > example:
            > > i've got an instance "n" of an "xmlNode" class
            > > i'd like to use "n.parentNo de" instead of "n.parent" ...[/color]
            > [snip]
            >
            > # try this ...
            > n.parentNode = n.parent[/color]

            i'll try,
            but ... it s not dynamic ....

            if n.parent change .... n.parentNode will not change ... it must be
            re-affected ... not ?



            Comment

            • Sean Ross

              #7
              Re: Adding method to object


              "marco" <marc.lentz@ctr ceal.caisse-epargne.fr> wrote in message
              news:bql820$uka $1@s1.read.news .oleane.net...[color=blue][color=green][color=darkred]
              > > > Is it possible to do the same thing for an attribut, instead of a[/color][/color][/color]
              method[color=blue]
              > ?[color=green][color=darkred]
              > > >
              > > > i'd like to wrap an newAttribute to an oldAttribute one :
              > > > example:
              > > > i've got an instance "n" of an "xmlNode" class
              > > > i'd like to use "n.parentNo de" instead of "n.parent" ...[/color]
              > > [snip]
              > >
              > > # try this ...
              > > n.parentNode = n.parent[/color]
              >
              > i'll try,
              > but ... it s not dynamic ....
              >
              > if n.parent change .... n.parentNode will not change ... it must be
              > re-affected ... not ?
              >[/color]

              You're right. Sorry about that. Maybe you could use a property?

              n.__class__.par entNode = property(lambda self: self.parent, ... etc ... )

              This way you can get/set/del n.parent using n.parentNode, and changes
              to n.parent will be reflect in n.parentNode.

              There's probably another way, but I can't think of it at the moment...

              Hope that's a little more helpful than the last suggestion,
              Sean



              Comment

              • marco

                #8
                Re: Adding method to object

                Sean Ross wrote:[color=blue]
                > "marco" <marc.lentz@ctr ceal.caisse-epargne.fr> wrote in message
                > news:bql820$uka $1@s1.read.news .oleane.net...
                >[color=green][color=darkred]
                >>>>Is it possible to do the same thing for an attribut, instead of a[/color][/color]
                >
                > method
                >[color=green]
                >>?
                >>[color=darkred]
                >>>>i'd like to wrap an newAttribute to an oldAttribute one :
                >>>>example:
                >>>>i've got an instance "n" of an "xmlNode" class
                >>>>i'd like to use "n.parentNo de" instead of "n.parent" ...
                >>>
                >>>[snip]
                >>>
                >>># try this ...
                >>>n.parentNo de = n.parent[/color]
                >>
                >>i'll try,
                >>but ... it s not dynamic ....
                >>
                >>if n.parent change .... n.parentNode will not change ... it must be
                >>re-affected ... not ?
                >>[/color]
                >
                >
                > You're right. Sorry about that. Maybe you could use a property?
                >
                > n.__class__.par entNode = property(lambda self: self.parent, ... etc ... )
                >
                > This way you can get/set/del n.parent using n.parentNode, and changes
                > to n.parent will be reflect in n.parentNode.
                >
                > There's probably another way, but I can't think of it at the moment...
                >
                > Hope that's a little more helpful than the last suggestion,
                > Sean
                >
                >
                >[/color]

                perfect ! it works like a charm
                thanx a lot !

                Comment

                • Dave Benjamin

                  #9
                  Re: Adding method to object

                  In article <72krsvcpeur8hh u74s4bhlsq3bf60 fu055@4ax.com>, Gonçalo Rodrigues wrote:[color=blue]
                  > If you want to leave out the f as arg (call it like an instance
                  > method) then
                  >[color=green][color=darkred]
                  >>>> import new
                  >>>> help(new.instan cemethod)[/color][/color]
                  > Help on class instancemethod in module __builtin__:
                  >
                  > class instancemethod( object)
                  > | instancemethod( function, instance, class)
                  > |
                  > | Create an instance method object.
                  > |
                  > ...
                  >
                  > And
                  >
                  > new.instancemet hod(incr, f, f.__class__)
                  >
                  > Should do the trick.[/color]

                  I tried to bring this up several weeks ago but nobody replied, so I'm
                  bringing it up again. I still see people recommending "new.instanceme thod",
                  yet "help(new)" says that the "new" module is deprecated. The seemingly
                  identical "types.MethodTy pe" ought to be its replacement, even though I
                  think "new.instanceme thod" is more clear. If you stringify types.MethodTyp e,
                  it says "<type 'instancemethod '>". The help for instancemethod, above, says
                  that instancemethod is in the __builtin__ module, but it is neither a
                  builtin nor available in the __builtin__ module. This is confusing. Can we
                  decide on a community standard for the appropriate way to create new
                  instance methods, and resolve the documentation discrepancies?

                  Thankya kindly,
                  Dave

                  --
                  ..:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:.
                  : d r i n k i n g l i f e o u t o f t h e c o n t a i n e r :

                  Comment

                  Working...