Sto provando ad intercettare le chiamate ai due metodi magici di sottolineatura di Python in nuove classi di stile. Questo è un esempio banale ma lo show di l'intento:Come posso intercettare le chiamate ai metodi "magici" di python in nuove classi di stile?
class ShowMeList(object):
def __init__(self, it):
self._data = list(it)
def __getattr__(self, name):
attr = object.__getattribute__(self._data, name)
if callable(attr):
def wrapper(*a, **kw):
print "before the call"
result = attr(*a, **kw)
print "after the call"
return result
return wrapper
return attr
Se uso che oggetto proxy intorno lista ottengo il comportamento previsto per i metodi non-magiche, ma la mia funzione wrapper è mai chiamato per i metodi di magia.
>>> l = ShowMeList(range(8))
>>> l #call to __repr__
<__main__.ShowMeList object at 0x9640eac>
>>> l.append(9)
before the call
after the call
>> len(l._data)
9
Se non ereditare da oggetto (prima linea class ShowMeList:
) tutto funziona come previsto:
>>> l = ShowMeList(range(8))
>>> l #call to __repr__
before the call
after the call
[0, 1, 2, 3, 4, 5, 6, 7]
>>> l.append(9)
before the call
after the call
>> len(l._data)
9
Come faccio a ottenere questo risultato intercetta con nuovi stili di classi?
Cosa stai veramente cercando di fare intercettando i metodi a doppia sottolineatura? O è solo per curiosità? – thesamet
Conservo sempre un elenco di tutti i metodi magici qui: https://github.com/niccokunzmann/wwp/blob/6df6d7f60893a23dc84a32ba244b31120b1241a9/magicMethods.py (generato, quindi funziona con Python 2 e 3) – User
In realtà sembra che quello che vuoi fare sia intercettare le chiamate ai metodi magici di _instances_ di una nuova classe di stile - comunque è comunque una buona domanda. – martineau