Adding method to object

marco marc.lentz at ctrceal.caisse-epargne.fr
Wed Dec 3 09:27:49 EST 2003


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.parentNode" instead of "n.parent" ...


"Gonçalo Rodrigues" <op73418 at mail.telepac.pt> a écrit dans le message de
news: 72krsvcpeur8hhu74s4bhlsq3bf60fu055 at 4ax.com...
> On Wed, 03 Dec 2003 10:44:12 +0100, "Thomas Guettler"
> <guettli at thomas-guettler.de> wrote:
>
> >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)
>
> 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
>
> >>> import new
> >>> help(new.instancemethod)
> Help on class instancemethod in module __builtin__:
>
> class instancemethod(object)
>  |  instancemethod(function, instance, class)
>  |
>  |  Create an instance method object.
>  |
> ...
>
> And
>
> new.instancemethod(incr, f, f.__class__)
>
> Should do the trick.
>
> With my best regards,
> G. Rodrigues






More information about the Python-list mailing list