在类中递归调用私有函数的python方法

2024-09-30 12:23:16 发布

您现在位置:Python中文网/ 问答频道 /正文

今天,我尝试在类中递归调用私有方法:

class Bot:
    def __init__(self, sudoku):
        """ init code """

    def __findJokers(self, target):
        """ some validations """
        self.__findJokers(target)

运行我的程序时,我收到:

^{pr2}$

经过一段时间的搜索,我发现可以使用instance._Bot__findJokers(somevalue)在类范围之外调用私有函数

但是,还有其他(或更好的)方法来调用类内部的私有函数?在


Tags: 方法函数self程序targetinitdefbot
2条回答

作为补充,如果您想知道为什么__findJokers方法只能从类方法内部访问,那么它的工作原理如下:

>>> dir(Bot)
['_Bot__findJokers', '__doc__', '__init__', '__module__']

在内部类字典中,__findJokers已重命名为_Bot_findJokers。在

那么让我们分解这个方法。在

^{pr2}$

在方法代码中,属性名也直接替换为_Bot_findJokers。 这里也可以观察到:

>>> Bot._Bot__findJokers.im_func.func_code.co_names
('_Bot_findJokers',)

这意味着最终,属性__findJokers从未真正存在过。在

如果你从外面打电话,你可能想要这样的东西:

class Bot:
    def __init__(self, sudoku):
        """ init code """
        pass

    # public access
    def findJokers(self, target):
        # forward to private
        return self.__findJokers(target)

    # private access
    def __findJokers(self, target):
        """ some validations """
        # hopefully you're doing something else,
        # since this is an infinite recursion.
        return self.__findJokers(target)

注意:您不必退货。在

相关问题 更多 >

    热门问题