Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 尝试使用嵌套函数搜索子体时出错_Python_Python 3.x_Recursion - Fatal编程技术网

Python 尝试使用嵌套函数搜索子体时出错

Python 尝试使用嵌套函数搜索子体时出错,python,python-3.x,recursion,Python,Python 3.x,Recursion,我有两个类,其中的对象分别包含关于个人和家庭的信息。person类中有一个函数,如果给定的人是后代,则该函数应返回true。我可以找到答案,但是我不知道在进行了几个嵌套函数调用之后如何返回它的值 这是我的两个函数,在不同的类中 函数,该函数最初被调用以查看子体是否存在。如果存在,我希望它返回true def checkIfDesc(self, person): for family in self.marriages: return families[family].fa

我有两个类,其中的对象分别包含关于个人和家庭的信息。person类中有一个函数,如果给定的人是后代,则该函数应返回true。我可以找到答案,但是我不知道在进行了几个嵌套函数调用之后如何返回它的值

这是我的两个函数,在不同的类中

函数,该函数最初被调用以查看子体是否存在。如果存在,我希望它返回true

def checkIfDesc(self, person):
    for family in self.marriages:
        return families[family].famDescendant(person)
来自另一个类的函数,该类保存有关族的信息。i、 给孩子们打电话

def famDescendant(self, person):
    for child in self.children:
        if person == child:
           return True
        else:
            return persons[child].checkIfDesc(person)
现在,我认为我的问题在于checkIfDesc函数及其返回语句。如果在第一次迭代中未找到子体,它将停止搜索。如果我删除return语句,基本上只是遍历从输出中可以看到的族,那么我输入person==child语句

任何帮助或提示都将不胜感激。

此功能

def checkIfDesc(self, person):
    for family in self.marriages:
        return families[family].famDescendant(person)
不会做你想做的事,正如你所发现的,因为如果self有几次婚姻,并且person不是第一次婚姻的后代,那么函数将返回False,而不会检查其他婚姻。您可以这样做:

def checkIfDesc(self, person):
    return any(families[family].famDescendant(person) for family in self.marriages)

一旦找到子体,将立即停止检查。

通过实施以下更改解决:

def checkIfDesc(self, person):
return any(families[family].famDescendant(person) for family in self.marriages)

def famDescendant(self, person):
    for child in self.children:
        if person == child:
           return True
        else:
            if (persons[child].checkIfDesc(person))
                return True
            else:
                continue:

谢谢,这肯定涵盖了一个我没有想到的场景!我还意识到它被卡在了FamFoundant函数中。通过您的编辑和我的编辑功能,程序可以正常工作。-谢谢