0

说我有两种方法first_methodsecond_method如下所示。

def first_method(some_arg):
    """
    This is the method that calls the second_method
    """

    return second_method(some_arg[1], some_arg[2])


def second_method(arg1, arg2):
    """
    This method can only be called from the first_method
    or it will raise an error.
    """

    if (some condition):
        #Execute the second_method
    else:
        raise SomeError("You are not authorized to call me!")

我如何检查(什么条件)第一种方法正在调用第二种方法并根据该方法处理该方法?

4

3 回答 3

4

为什么不在第一个方法中定义第二个方法,这样它就不会被直接调用。

例子:

def first_method(some_arg):
    """
    This is the method that calls the second_method
    """
    def second_method(arg1, arg2):
        """
        This method can only be called from the first_method
        hence defined here
        """

        #Execute the second_method


    return second_method(some_arg[1], some_arg[2])
于 2012-12-21T05:49:55.700 回答
1

您可以查看检查模块中的一些堆栈函数。

但是,您正在做的事情可能是个坏主意。尝试强制执行此类事情根本不值得麻烦。只需记录不应该直接调用第二种方法,给它一个带有前导下划线(_secret_second_method或其他)的名称,然后如果有人直接调用它,那是他们自己的问题。

或者,只是不要将其设为单独的方法,而是将代码直接放入first_method. 如果它从不从一个地方调用,为什么你需要让它成为一个单独的函数?在这种情况下,它也可能是第一种方法的一部分。

于 2012-12-21T05:45:02.040 回答
1

这是一个与 Django 无关的示例,说明如何获取调用方方法框架(该框架中有很多信息):

import re, sys, thread

def s(string):
    if isinstance(string, unicode):
        t = str
    else:
        t = unicode
    def subst_variable(mo):
        name = mo.group(0)[2:-1]
        frame = sys._current_frames()[thread.get_ident()].f_back.f_back.f_back
        if name in frame.f_locals:
            value = t(frame.f_locals[name])
        elif name in frame.f_globals:
            value = t(frame.f_globals[name])
        else:
            raise StandardError('Unknown variable %s' % name)
        return value
    return re.sub('(#\{[a-zA-Z_][a-zA-Z0-9]*\})', subst_variable, string)

first = 'a'
second = 'b'
print s(u'My name is #{first} #{second}')

基本上,您可以使用sys._current_frames()[thread.get_ident()]获取帧链表头(每个调用者的帧),然后查找您想要的任何运行时信息。

于 2012-12-21T05:49:32.757 回答