2013-08-28 68 views
1

下面的方法查找字符串以查找它是否有任何python方法。return语句在python递归中不返回任何东西

def there_is_a_call(string): 
    return string.find('(') > -1 

def find_and_remove_functions(string , found_functions): 
    if not there_is_a_call(string): 
     print(found_functions) 
     return found_functions 
    else: 
     function_end = string.find('(') 
     function_string = string[:function_end][::-1] 
     if function_string.find('.') > -1 : 
      index = function_string.find('.') 
     elif function_string.find(' ') > -1: 
      index = function_string.find(' ') 
     else: 
      index = len(function_string) - 1 
     func_name  = function_string[ : index + 1 ][::-1] + '()' 
     new_list = found_functions 
     new_list.append(func_name) 
     find_and_remove_functions(string[ function_end + 1: ], found_functions) 

所以我试着看看它是否有效,然后发生这种情况;

>>>> a = find_and_remove_functions('func() and some more()' , []) 
['func()', ' more()'] 
>>>> print(a) 
None 

为什么return语句不返回任何东西,而found_functions做得到印刷?

+0

的'return'声明_is_返回的东西......但如果'if'不错,唯一的执行。否则,你正在运行其他代码,它不会返回任何东西。它递归地调用该函数,但它对递归调用的结果不起作用。通常情况下,递归情况下的最后一行是一个返回值,它返回递归调用的值或者围绕它构建的表达式。 – abarnert

回答

2

这里:

find_and_remove_functions(string[ function_end + 1: ], found_functions) 

应该

return find_and_remove_functions(string[ function_end + 1: ], found_functions) 
1

一些更多的解释在这里。

a = find_and_remove_functions('func() and some more()' , [])打印一个列表,因为有一行print(found_functions)正在执行。

a被分配到find_and_remove_functions结果,并且由于功能设置的递归调用(看你else部分没有return)后没有返回,就被分配到None

这里是正在发生的事情的一个简单的例子:

>>> def test(): 
...  print "test" 
... 
>>> a = test() 
test 
>>> print(a) 
None 
>>> a is None 
True 
+0

你需要解释为什么调用'find_and_remove_functions'为什么不返回。毕竟,基地里有一个“回报”。这只是递归的情况下不返回从基本情况返回的东西。所以OP需要做karthikr的回答。 – abarnert

+0

@abarnert肯定,更新了答案。完全同意OP应该做karthikr建议的事情。谢谢! – alecxe