replacing instance __setattr__

Tim Peters tim.one at comcast.net
Tue Jul 9 00:23:55 EDT 2002


[Aahz]
> <scratch head>  Your argument appears to be failing my duck test:
>
>     import new
>
>     class C:
>         def __init__(self, val):
>             self.val = val
>
>     def __str__(self):
>         return str(self.val).upper()
>
>     x = C('foo')
>     x.__str__ = new.instancemethod(__str__, x, C)
>     print str(x)
>
> What am I missing?

Try deriving C from object and see what it prints.  This is an area where
new-style classes behave more rationally.  x.__str__ ends up being a bound
method object in either case (which, despite the "method" in the name, is
not a method -- it's just a callable function at that point, and is a data
attribute of x).  Old-style classes do look at data attributes first;
new-style classes don't; and I do believe I was unclear about that
distinction.  BTW, bound method objects aren't methods because they're bound
<wink>:  the OO part of "a method" is the part that figures out where to
dispatch to, and in a bound method object that part has already been
computed and frozen (cached in the BMO).  At the point it's just a flavor of
ordinary function.






More information about the Python-list mailing list