27 de fevereiro de 2008

Magia: Adicionando métodos à class por meio da instância

Um pouco de magia. Nada de mais.


>>> class Wakadoo(object): pass

>>> wakadoo = Wakadoo()
>>> # Lets create a function to be add to the 'wakadoo' object.
>>> def __setattr__(self, name, value):
self.__dict__[name] = value
print "Congrats. This method worked."


>>> # Look, the magic...
>>> setattr(wakadoo.__class__, __setattr__.func_name, __setattr__)
>>>
>>> wakadoo.var = "Ah-ha!"
Congrats. This method worked.
>>>
>>> print wakadoo.var
Ah-ha!
>>>

Nenhum comentário: