反正有做這樣的事情:Python可以判斷類的對象的訪問方法
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
它不適合提供的所有原因,但爲響應感謝:他們是一個很大的幫助。
你提到你有大量的類互相調用。您似乎試圖插入某種「安全性」,以限制允許哪些類執行什麼操作。這通常是一個壞主意。 請解釋你爲什麼要這樣做,也許有人可以想出一個更好的解決方案的用例。 – 2009-09-30 12:41:01
你在做rong – Triptych 2009-09-30 14:36:22