Python3:将函数内的函数调用到另一个函数,怎么做?

时间:2018-01-26 23:29:12

标签: python function higher-order-functions

这是代码示例

import random
def randomNum():
    i = random.randint(1,10)
    return i

这只是添加上下文

以下是问题所在的地方

def function1():
    randomNum()
    r = randomNum()
    if r = 2:
        #do something
        def function2():
            return True

这是函数1中的函数2,我想在函数3上调用

def function3():
    #some code
    function = function2()
    if function == True:  #this last 2 lines is what i'm trying to achieve
        #do something

建议?

1 个答案:

答案 0 :(得分:1)

问题是function1会返回None,但它应该返回function2。在function3中,只需检查if function is not None: 所以,像:

In [1]: import random
   ...: def randomNum():
   ...:     i = random.randint(1,4)
   ...:     return i
   ...:
   ...: def function1():
   ...:     randomNum()
   ...:     r = randomNum()
   ...:     print(r)
   ...:     if r == 2:
   ...:         #do something
   ...:         def function2():
   ...:             return True
   ...:         return function2
   ...:
   ...: def function3():
   ...:     function = function1()
   ...:     if function is not None:
   ...:         print("Did stuff")
   ...:     else:
   ...:        print("didn't do stuff")
   ...:

行动中:

In [2]: function3()
4
didn't do stuff

In [3]: function3()
1
didn't do stuff

In [4]: function3()
3
didn't do stuff

In [5]: function3()
4
didn't do stuff

In [6]: function3()
3
didn't do stuff

In [7]: function3()
2
Did stuff

In [8]: function3()
4
didn't do stuff

In [9]: function3()
2
Did stuff