IsPython really O-O?
Andrew Dalke
dalke at dalkescientific.com
Tue Nov 13 13:59:00 EST 2001
Adam Spitz wrote a bunch, including:
>First example that comes
>to mind: adding methods to an existing class. In Smalltalk, I'd just
>browse over to that class and add the method. In Ruby, I'd just write:
>
>class MyClass
> def newMethod()
> print "new method"
> end
>end
[in Python]
>def MyClass_newMethod(self):
> print "new method"
>MyClass.newMethod = MyClass_newMethod
I've been toying around with proposing
def MyClass.newMethod(self):
print "new method"
but I've never really needed it. Better I think would be if
Python's IDE's offered a reload() which was closer to Smalltalks's,
where a modified class definition propagates even to existing
instances of that class. So someone could edit a module and
manipulate things interactively without having to reload and rerun
everything.
> In Python, it feels like I'm sneakily hacking an
>extra method into a class against its will. (Does that make any sense?
>Maybe I'm being too touchy-feely. :)
When I first started Python, I wrote a class like:
class Spam:
def __init__(self, x):
self.x = x
def show(self):
print self.x
After I figured out it worked, I wanted to add a new method, so
I did
class Spam:
def double(self):
self.x = self.x * 2
then was annoyed that it didn't work the way I expected. So I
don't think you are alone in this view. I bring it up here because
I suspect for many people this is forgotten amoung all the other
confusions in the early stages of learning Python.
>Oh, and I've been meaning to ask - is there a way for me to add
>methods to Dict or List or String? I couldn't figure out how to do it,
>and that's where I *really* want it.
No. You can only add them to subclasses of those types, and
only in Python 2.2. You *can* add them to UserDict, UserList, and
UserString.
I've never liked that idea though (which Smalltalk and Ruby both
have). I think adding methods to an existing class is like
playing around with global variables. What's to keep two different
libraries from adding a method with the same name but which
does different things?
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list