反正有没有做这样的事情:
class A:
def foo(self):
if isinstance(caller, B):
print "B can't call methods in A"
else:
print "Foobar"
class B:
def foo(self, ref): ref.foo()
class C:
def foo(self, ref): ref.foo()
a = A();
B().foo(a) # Outputs "B can't call methods in A"
C().foo(a) # Outputs "Foobar"
调用者在哪里A
使用某种形式的自省来确定调用方法对象的类?
编辑:
最后,我根据一些建议将其放在一起:
import inspect
...
def check_caller(self, klass):
frame = inspect.currentframe()
current = lambda : frame.f_locals.get('self')
while not current() is None:
if isinstance(current(), klass): return True
frame = frame.f_back
return False
由于提供的所有原因,它并不完美,但感谢您的回复:他们提供了很大的帮助。