Python是否可以确定访问方法的对象的类 [英] Can Python determine the class of an object accessing a method
问题描述
反正有做这样的事情吗?
Is there anyway to do something like this:
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
中的 caller 使用某种自省形式来确定调用方法的对象的类吗?
Where caller in A
uses some form of introspection to determine the class of the calling method's object?
编辑:
最后,我根据一些建议将它们放在一起:
In the end, I put this together based on some of the suggestions:
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
由于提供的所有原因,它并不完美,但是感谢您的答复:它们是一个很大的帮助.
It's not perfect for all the reasons supplied, but thanks for the responses: they were a big help.
推荐答案
假设调用者是一个方法,那么可以,通过查看上一帧,然后从本地人中选择self
,可以.
Assuming the caller is a method, then yes you can, by looking in the previous frame, and picking out self
from the locals.
class Reciever:
def themethod(self):
frame = sys._getframe(1)
arguments = frame.f_code.co_argcount
if arguments == 0:
print "Not called from a method"
return
caller_calls_self = frame.f_code.co_varnames[0]
thecaller = frame.f_locals[caller_calls_self]
print "Called from a", thecaller.__class__.__name__, "instance"
Üglŷ挺不错的,但是行得通.现在,为什么您要执行此操作完全是另一个问题,我怀疑还有更好的方法.不允许将A的整个概念称为B的错误.
Üglŷ as heck, but it works. Now why you would want to do this is another question altogether, I suspect that there is a better way. The whole concept of A isn't allowed to call B is likely to be a mistake.
这篇关于Python是否可以确定访问方法的对象的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!