限制仅通过其他方法调用的方法? [英] Limit a method to be called only through another method?

查看:162
本文介绍了限制仅通过其他方法调用的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有两种方法 first_method second_method 如下。

  def first_method(some_arg):

这是调用second_method
的方法

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


def second_method(arg1,arg2):

此方法只能从first_method
调用,否则会引发错误


if(some condition):
#Execute the second_method
else:
raise SomeError(你无权打电话给我!)

我如何检查(第一种方法)第二种方法的第二种方法,并按照这种方法处理方法?

解决方案

您可以查看中的某些堆栈功能检查odule



然而,你在做什么可能是一个坏主意。试图执行这种事情根本不值得。只需记录第二种方法不应该被直接调用,给它一个带有前导下划线( _secret_second_method 或其他)的名称,然后如果有人直接调用它就是自己的问题。



或者,只是不要使它成为一个单独的方法,并将代码放在 first_method 中。如果从一个地方去除它,你为什么需要使它成为一个单独的功能?在这种情况下,它也可能成为第一种方法的一部分。


Say i have two methods first_method and second_method as follows.

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!")

How can i check (what condition(s)) that second method is being called by the first method and process the method according to that ?

解决方案

You could look at some of the stack functions in the inspect module.

However, what you are doing is probably a bad idea. It simply isn't worth the trouble to try to enforce this sort of thing. Just document that the second method is not supposed to be called directly, give it a name with a leading underscore (_secret_second_method or whatever), and then if anyone calls it directly it's their own problem.

Alternatively, just don't make it a separate method and put the code right in first_method. Why do you need to make it a separate function if it's never called except from one place? In that case it might as well be part of the first method.

这篇关于限制仅通过其他方法调用的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆