无论如何要做这样的事情:
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"
Run Code Online (Sandbox Code Playgroud)
调用者在哪里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 …Run Code Online (Sandbox Code Playgroud)