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

发布于 2021-01-29 17:26:31

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

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

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

关注者
0
被浏览
49
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    假设调用方是一种方法,那么可以,通过查看前一帧并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"
    

    Üglŷ挺不错的,但是行得通。现在,为什么要执行此操作是另一个问题,我怀疑还有更好的方法。不允许将A的整个概念称为B可能是一个错误。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看