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 3.x 从列表中随机选择一个函数,然后对结果应用条件_Python 3.x_Function_If Statement_Random_Choice - Fatal编程技术网

Python 3.x 从列表中随机选择一个函数,然后对结果应用条件

Python 3.x 从列表中随机选择一个函数,然后对结果应用条件,python-3.x,function,if-statement,random,choice,Python 3.x,Function,If Statement,Random,Choice,a、b和c是预定义的函数,它们是更大代码的一部分。 代码始终返回elif部分,即使选择为敌方定义 我试着打印每一个,但什么也没发生 a = enemy_hit b = enemy_def c = enemy_sphit d = [a,b,c] enemyresponse = random.choice(d)() #print(enemyresponse) if enemyresponse == b : thing.health = thing.health - 0.25 #print

a、b和c是预定义的函数,它们是更大代码的一部分。 代码始终返回elif部分,即使选择为敌方定义 我试着打印每一个,但什么也没发生

a = enemy_hit
b = enemy_def
c = enemy_sphit
d = [a,b,c]
enemyresponse = random.choice(d)()
#print(enemyresponse)
if enemyresponse == b :
   thing.health = thing.health - 0.25
   #print(enemyresponse)
elif enemyresponse != b :
     #print(enemyresponse)
     thing.health = thing.health - 1
敌方响应永远不会等于b*,因为敌方响应是函数的返回值,而不是函数本身。请注意在随机选择函数后如何立即调用该函数:

random.choice(d)()
#               ^Called it
保存在名为selected_function或类似变量中选择的函数,然后对照该变量进行检查

你的意思可能是这样的未经测试:

a = enemy_hit
b = enemy_def
c = enemy_sphit
d = [a,b,c]

# Randomly get function from list
chosen_function = random.choice(d)

# Call it to get the return value
func_return = chosen_function()
print(func_return)

if chosen_function == b:
   thing.health = thing.health - 0.25

else:
   thing.health = thing.health - 1

*除非b本身返回,这似乎不太可能。

这是一种解决方法吗?我可以不调用而随机选择吗?我的意思是,我可以用if\else语句调用它吗?或者,如果我没有将函数分配给variables@HasanFares是的,只是不要把电话后的选择。正是这些括号导致函数被调用。我尝试过,但它返回的结果是:函数开始..敌人在0x005E84F8>@HasanFares,这是所选函数。你需要找个地方。敌方响应是一个函数,而不是一个值。@HasanFares请查看更新的代码。我已经把它修好了,所以它可读性好,冗余少。