PDA

View Full Version : cosa è il monkey patching?


ratman511
21-03-2010, 11:58
ho fatto qualche ricerca ma non l'ho capito. se potessi vedere un pò di codice python ad esempio e capire cosa è sarebbe una cosa ottima :D

cdimauro
21-03-2010, 12:39
>>> class c:
... def f(self): print 'f!'
>>> a = c()
>>> a.f()
f!
>>> def g(self):
... print 'g!'
>>> c.g = g
>>> a.g()
g!
>>> def h(x):
... print 'x:', x
>>> a.h = h
>>> a.h(1)
x: 1
>>> b = c()
>>> b.h(1)
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
b.h(1)
AttributeError: c instance has no attribute 'h'
>>> del c.f
>>> a.f()
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
a.f()
AttributeError: c instance has no attribute 'f'
:D

DanieleC88
21-03-2010, 14:15
>>> class c:
... def f(self): print 'f!'
>>> a = c()
>>> a.f()
f!
>>> def g(self):
... print 'g!'
>>> c.g = g
>>> a.g()
g!
>>> def h(x):
... print 'x:', x
>>> a.h = h
>>> a.h(1)
x: 1
>>> b = c()
>>> b.h(1)
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
b.h(1)
AttributeError: c instance has no attribute 'h'
>>> del c.f
>>> a.f()
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
a.f()
AttributeError: c instance has no attribute 'f'
:D

Wow, l'esempio mi è piaciuto moltissimo, meglio questo che mille parole. :D