return statement doesnt return anything in python

2020-04-30 01:58发布

问题:

The methods below look in a string to find if it has any python methods.

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 )

So I try to see if it works and then this happens;

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

Why is the return statement not returning anything while the found_functions do get printed?

回答1:

Here:

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

should be

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


回答2:

Some more explanation here.

a = find_and_remove_functions( 'func() and some more()' , [] ) prints a list because there is a line print( found_functions ) being executed.

a is assigned to the result of find_and_remove_functions and, since the function returns nothing after the set of recursive calls (see your else part doesn't have a return), it is assigned to None.

Here's a simple example of what is happening:

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