2010-03-05 14 views
3

Si j'ai ceci:Python - Puis-je accéder à l'objet qui m'appelle?

class A: 
    def callFunction(self, obj): 
     obj.otherFunction() 

class B: 
    def callFunction(self, obj): 
     obj.otherFunction() 

class C: 
    def otherFunction(self): 
     # here I wan't to have acces to the instance of A or B who call me. 

... 

# in main or other object (not matter where) 
a = A() 
b = B() 
c = C() 
a.callFunction(c) # How 'c' know that is called by an instance of A... 
b.callFunction(c) # ... or B 

Malgré la conception ou d'autres problèmes, c'est seulement une question d'un esprit curieux.

Note: Ceci doit être fait sans changerotherFunctionsignature

Répondre

11

Si cela est à des fins de débogage, vous pouvez utiliser inspect.currentframe():

import inspect 

class C: 
    def otherFunction(self): 
     print inspect.currentframe().f_back.f_locals 

Voici la sortie:

>>> A().callFunction(C()) 
{'self': <__main__.A instance at 0x96b4fec>, 'obj': <__main__.C instance at 0x951ef2c>} 
1

Examinez la pile avec le inspect module avec inspect.stack(). Vous pouvez alors obtenir l'instance de chaque élément dans la liste avec f_locals['self']

+0

Mais je veux OBJECT qui acces me appelle .. pas seulement le nom de la classe .. Je wan't à l'instance acces –

+0

Utilisez le module pour inspecter l'accès ' tb_frame' dans chaque élément de la pile et ensuite vous pouvez trouver l'occurrence dans 'f_locals ['self']' –

3

Voici un hack rapide, obtenir la pile et de la dernière image obtenir la population locale d'accéder à l'auto

class A: 
    def callFunction(self, obj): 
     obj.otherFunction() 

class B: 
    def callFunction(self, obj): 
     obj.otherFunction() 

import inspect 

class C: 
    def otherFunction(self): 
     lastFrame = inspect.stack()[1][0] 
     print lastFrame.f_locals['self'], "called me :)" 

c = C() 

A().callFunction(c) 
B().callFunction(c) 

sortie:

<__main__.A instance at 0x00C1CAA8> called me :) 
<__main__.B instance at 0x00C1CAA8> called me :)