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

drew moore drew at astro.pas.rochester.edu
Sat Feb 17 22:06:59 CET 2007


> OK, looking into my original code, Test.Func1 was a Function, Test.Func2 was
> a Bound Method, and MyClass.Func2 was an unbound method.
> My question then is: Why is Test.Func1 not a bound method?
>   
This isn't really an IronPython question but...

After you use Python for a while, you'll realize that such behavior 
would be very bad.

An instance might want to simply cache a function for usage later. If 
just putting the function into the instance dictionary changed its 
signature, that would be a Bad Thing. Being able to add methods to a 
class at runtime for ALL instances to use -- well, that is a Good Thing.

If you want to override the behavior of the class in specific instances, 
you probably want those instances to be subclasses instead.

If you want to change that behavior *at runtime*, you can dynamically 
change an instance's class::

inst.__class__ = SomeOtherClass

What are you trying to do that is leading you to desire this behavior? 
Your question might not seem so silly (sorry) if we can see the problem 
you are trying to solve. I'm sure that once you see the "Pythonic" way 
to do it, you'll like it better.

 >>> class spam : pass
...
 >>> def eggs(self) : print self
...
 >>> spam.eggs = eggs
 >>> spam.eggs is eggs
False
 >>> eggs
<function eggs at 0x00A50330>
 >>> spam.eggs
<unbound method spam.eggs>
 >>> s = spam()
 >>> s.eggs is eggs
False
 >>> s.eggs
<bound method spam.eggs of <__main__.spam instance at 0x00A4EAA8>>
 >>> s.eggs = eggs
 >>> s.eggs is eggs
True
 >>> s.eggs
<function eggs at 0x00A50330>
 >>> s.__class__
<class __main__.spam at 0x008F9330>
 >>> class OldSpam(spam) :
...         def eggs(self) :
...                 print 42
...
 >>> os = OldSpam()
 >>> os.eggs()
42
 >>> s.eggs()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: eggs() takes exactly 1 argument (0 given)
 >>> del s.eggs
 >>> s.eggs()
<__main__.spam instance at 0x00A4EAA8>
 >>> s.__class__ = OldSpam
 >>> s.eggs()
42
 >>>

Hope this helps.

cheers

Drew




More information about the Ironpython-users mailing list