English 中文(简体)
Can-030确定使用某种方法的物体类别
原标题:Can Python determine the class of an object accessing a method
  • 时间:2009-09-30 11:58:36
  •  标签:

是否有这样的办法:

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"

<<><<>>><>><>>>>> 采用某种形式的内tro,以确定点火方法的类别?

www.un.org/Depts/DGACM/index_spanish.htm

最后,我根据以下一些建议把这一点放在一起:

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

由于提供的所有原因,它并非完美无缺,而是由于这些答复:它们是一个很大的帮助。

最佳回答

假设打电话是一种方法,那么你可以通过在以前的框架中考察并从当地人那里取出<条码>。

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ŷ as heck, but it work. 现在,既然你想要这样做是另一个问题,我怀疑有更好的办法。 A isn t允许称作B的整个概念很可能是错误的。

问题回答

打电话者总是A。 你在B方法中重新称呼这一事实并没有改变。 换言之:Insiode B.foo,ref is an instance of Arefoo ( is a calls on A, B>>, is not involved on that calls (it could take up-level).

唯一停用的办法是通过<代码>自行。 因此,如果是B,可以检查。

class A(object):
    def foo(self, caller=None):
        if isinstance(caller, B):
           print "B can t call methods in A"
        else:
           print "Foobar"

class B(object):
    def foo(self, ref): ref.foo(self)

class C(object):
    def foo(self, ref): ref.foo(self)

a = A();
B().foo(a)    # Outputs "B can t call methods in A"
C().foo(a)    # Outputs "Foobar"
a.foo()       # Outputs "Foobar"

满足你们的需求可能更好:

class A(object):
    def foo(self):
        # do stuff

class B(A):
    def foo(self):
        raise NotImplementedError

class C(A):
    pass

......但是,在不知情的情况下很难说你想要做什么。





相关问题
热门标签