loose methods : Smalltalk asPython

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Wed Dec 27 03:03:12 EST 2006


On Tue, 26 Dec 2006 22:49:30 -0500, Jan Theodore Galkowski wrote:

> Hi.
> 
> One of the things I'd like to do with Python is find a way to
> consistently implement Smalltalk's "loose methods".  This is a
> capability whereby additional  methods can be added dynamically to
> existing classes.

You can't modify the built-in classes. I'm not sure that it is a good idea
to allow built-ins to be modified. When I see an int, I like the fact that
I know what the int can do, and I don't have to worry about whether it has
been modified by some piece of code elsewhere.

But custom classes can be modified (the risk of some other code modifying
it is the price you pay for being able to customise the class in the first
place):

>>> class MyInt(int):
...     pass
...
>>> def odd(self):
...     return bool(self % 2)
...
>>> MyInt.odd = odd
>>> n = MyInt(5)
>>> n.odd()
True


> In some respects, it's possible with Python. While "object" cannot be
> touched, it's possible to define
> 
>    class MutableObject( object ) :  pass ;
> 
> and derive subclasses from MutableObject instead of object.  Thereafter,
> for instance, if devising a class
> 
>    class Foo( MutableObject ) :   isFoo = True ;   ...
> 
> you can also put in its module
> 
>     MutableObject.isFoo = False ;
> 
> So, at least for the inheritance hierarchy descending from
> MutableObject, for an arbitrary object instance x,
> 
>     x.isFoo
> 
> will return whether it's a Foo or not, effectively although not
> transparently extending the builtin type(.).

Why not just say isinstance(x, Foo)?


> Like, then, what of other classes which descend from object and not
> MutableObject?  You'd love to be able to set methods and attributes
> within them.  Can you?  

Yes you can. Did you bother to try it?

>>> class Shrubbery(object):
...     pass
...
>>> Shrubbery.spam = lambda self, n: repr(self) + "spam"*n
>>>
>>> Shrubbery().spam(5)
'<__main__.Shrubbery object at 0xb7d06aec>spamspamspamspamspam'



-- 
Steven.




More information about the Python-list mailing list