Perl/Python/Ruby common backend (Parrot, can Ruby play too?)
dalke at acm.org
Tue Aug 7 19:23:59 CEST 2001
Erno Kuusela wrote:
>you can do this:
>>>> def new_eat(self):
>... print 'yech'
>>>> Spam.eat = new_eat
I do want to emphasize that this isn't a need of mine. I brought
this up as part of a Ruby/Python comparison, and I was stating that
I don't think adding new methods to an existing class is a good
practice. Python's "magic incantation" as you call it is more
the way I prefer things, unlike in Ruby where this sort of technique
seems to be encouraged.
I mentioned the only case I've come across where someone wanted
to add a method dynamically to existing classes and all existing
instances, which was a development system meant for non-programmers
where there should be an easy way to change the system without
having to keep track of all the instance dependencies. The
researcher on this system (as I recall) decided against Python
because it requires a non-standard/magic way to do this.
I don't have the use cases to help determine what would be a
better system. There are dozens of possible solutions.
BTW, your trick of attaching functions to the class has its
own brand of magic:
>>> class Spam:
>>> import math
>>> Spam.cos = math.cos
>>> def my_cos(x):
... return math.cos(x)
>>> Spam.my_cos = my_cos
>>> spam = Spam()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: too many arguments to my_cos(); expected 1, got 2
This is because builtin functions aren't bound into a method
reference, while Python functions are - something I regard
as a wart in Python, as the result is implementation dependent.
But at least it's documented :)
dalke at dalkescientific.com
More information about the Python-list