【问题标题】:randomly choosing a function from a list then apply conditions to the result从列表中随机选择一个函数,然后将条件应用于结果
【发布时间】:2017-05-16 16:36:30
【问题描述】:

a 、 b 和 c 是预定义函数,它们是更大代码的一部分。 即使选择是enemy_def,代码也总是返回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

【问题讨论】:

    标签: python-3.x function if-statement random choice


    【解决方案1】:

    enemy_reponse 永远不会等于b*,因为enemy_reponse 是函数的返回值,而不是函数本身。请注意在随机选择该函数后如何立即调用它:

    random.choice(d)()
    #               ^Called it
    

    将选择的函数保存在名为chosen_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 语句中调用它,或者如果我没有将函数分配给变量,我可以这样做
    • @HasanFares 是的,只是不要在调用choice 之后添加()。正是这些括号导致函数被调用。
    • 我试过了,但它返回的只是:函数开始。.enemy_sphit at 0x005E84F8>
    • @HasanFares 这就是选择的函数。你需要在某个地方调用它。 enemy_reponse 是一个函数,而不是一个值。
    • @HasanFares 查看更新后的代码。我已经把它修好了,这样它就更易读了,而且冗余更少。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    • 2021-12-15
    • 2016-03-02
    • 2017-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多