Python可以确定访问方法的对象的类

bla*_*kef 2 python introspection

无论如何要做这样的事情:

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
    return False
Run Code Online (Sandbox Code Playgroud)

由于提供的所有原因,它并不完美,但感谢您的回复:它们是一个很大的帮助.

Len*_*bro 6

假设调用者是一种方法,那么你可以通过查看前一帧并self从当地人中挑选出来.

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"
Run Code Online (Sandbox Code Playgroud)

Üglŷ哎呀,但它确实有效.既然你想要这样做的原因完全是另一个问题,我怀疑有更好的方法.A的整个概念不允许调用B可能是一个错误.

  • 在很多情况下失败:调用方法顶级,在自由函数中调用方法,使用另一个名称为"self"(使用`self`只是一个约定),等等 (2认同)