とにかくこのようなことをすることはありますか?
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
提供されたすべての理由で完璧ではありませんが、回答に感謝します。彼らは大きな助けになりました。