Asociación de métodos en tiempo de ejecución en Python

Este post fue migrado de un blog hecho con Wordpress. Si se ve mal, dejame un comentario y lo arreglo.

En el primer artículo de La Historia de Python (en) se menciona, entre las cualidades que hacen a Python un lenguaje que permite la programación orientada a objetos, la posibilidad de "asociación de métodos en tiempo de ejecución" ("run-time binding of methods"). Hoy en otro artículo del autor, vuelvo a leer sobre el tema:

Now instances of C have a method with one argument named 'meth' that works exactly as before. It even works for instances of C that were created before the method was poked into the class.

Vamos a ver un ejemplo de esto:

>>> class C:

...     pass

...

>>> c1 = C()

>>> c1.hello()

Traceback (most recent call last):

  File "", line 1, in 

AttributeError: C instance has no attribute 'hello'

>>> def hello(myself, name):

...     myself.lasthello = name

...     print "Hello %s" % name

...

>>> C.hello = hello

>>> c2 = C()

>>> c2.hello("mary")

Hello mary

>>> c1.hello("juanjo")

Hello juanjo

Comentarios

Comments powered by Disqus