2011-01-13 12 views

risposta

30

partire Python 2.6 è possibile utilizzare l'attributo speciale __self__:

>>> a.some.__self__ is a 
True 

im_self è stata eliminata in py3k.

Per i dettagli, vedere la inspect module in the Python Standard Library.

+1

Giusto per rendere del tutto chiaro: utilizzare questo se si dispone di Python 3. Se si sta utilizzando Python 2, l'equivalente è il 'im_self' che altri hanno scritto. –

+2

@Thomas: funziona perfettamente per me in python2.x stabile – SilentGhost

+0

Errore mio, non leggerei la risposta con sufficiente attenzione. –

7
>>> class A(object): 
... def some(self): 
...  pass 
... 
>>> a = A() 
>>> a 
<__main__.A object at 0x7fa9b965f410> 
>>> a.some 
<bound method A.some of <__main__.A object at 0x7fa9b965f410>> 
>>> dir(a.some) 
['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__format__', '__func__', '__get__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'im_class', 'im_func', 'im_self'] 
>>> a.some.im_self 
<__main__.A object at 0x7fa9b965f410> 
3

prova a seguire il codice e vedere, se ti aiuta:

a.some.im_self 
3

Volete qualcosa di simile credo:

>>> a = A() 
>>> m = a.some 
>>> another_obj = m.im_self 
>>> another_obj 
<__main__.A object at 0x0000000002818320> 

im_self è l'oggetto istanza della classe.

Problemi correlati