[IronPython] Method invocation when assigned to instancediffers from default assignment?

Simon Dahlbacka simon.dahlbacka at gmail.com
Wed Feb 21 08:16:44 CET 2007


<snip>

>
> -----Original Message-----
> Here's a simple scenario I can think of where instances might have
> callable
> attributes that don't need (or want) self automatically put in as the
> first
> argument:
> --Reply--
> But see, wouldn't it be nice, in your example, to do this:
>
> import sys
> class Logger(object) :
>     writer = sys.stdout.write
>     def __init__(self, writer=None) :
>         if writer is not None :
>             self.writer = writer
>     def Log(self, message) :
>         self.writer(message)
>
> Temp = Logger()
> OtherTemp = Logger()
> ErrorLog = Logger(sys.stderr.write)
> #At a later point in time...
> messageCount = 0
> def myLogger(message):
>     global messageCount
>     messageCount += 1
>     sys.stdout.write("<" + str(messageCount) + ">" + message)
> Logger.writer = myLogger
> Temp.Log("SomeMessage")
> OtherTemp.Log("SomeMessage")
> ErrorLog.Log("SomeError")
>
> As neither Temp nor TempOther have their own instanced function, Log would
> have to fallback on the class function, which is now different, just like
> any other class variable. But we can't do that as a function attached to a
> class is considered an unbound method.
> This inconsistency is what has me confused about the utility of this
> ability.


FWIW,
if you want to add a new instance method to  an already instantiated class,
in python you can do

import new

Temp.writer = new.instancemethod(myLogger, Temp, Logger)

(Haven't tried it IronPython though..)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/ironpython-users/attachments/20070221/ad830980/attachment.html>


More information about the Ironpython-users mailing list