Perl/Python/Ruby common backend (Parrot, can Ruby play too?)
Andrew Dalke
dalke at acm.org
Tue Aug 7 13:23:59 EDT 2001
Erno Kuusela wrote:
>you can do this:
>>>> def new_eat(self):
>... print 'yech'
>...
>>>> Spam.eat = new_eat
>>>>
>>>> spam.eat()
>yech
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:
... pass
...
>>> import math
>>> Spam.cos = math.cos
>>> def my_cos(x):
... return math.cos(x)
...
>>> Spam.my_cos = my_cos
>>> spam = Spam()
>>> spam.cos(0)
1.0
>>> spam.my_cos(0)
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.
http://groups.google.com/groups?hl=en&safe=off&th=f16901b55fd6962b,6&seekm=8
j83ml%242s7%241%40slb3.atl.mindspring.net#p
But at least it's documented :)
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list