简体   繁体   English

您可以在while循环中更改函数名称吗-python3

[英]Can you change function names a in while loop - python3

I was wondering if you can change function names while in a while loop?我想知道您是否可以在 while 循环中更改函数名称? For example, if I had an X amount of functions called function1, function2, function3, functionX, could I execute the function with the loop number tracker?例如,如果我有 X 个名为 function1、function2、function3、functionX 的函数,我可以使用循环编号跟踪器执行该函数吗? Something like this:像这样的东西:

def function1():
    do this

def function2():
    do that

def function3():
    do something

def...

i = 1

while i <= X:
    function(i)
    i += 1

Obviously this doesn't work, but is there a way to make it work?显然这行不通,但有没有办法让它工作?

EDIT: I'm new to python so I wanted to try to make a simple project rather than watching tutorials.编辑:我是 python 新手,所以我想尝试做一个简单的项目而不是看教程。 I'm, trying to make a "hangman" game.我正在尝试制作“刽子手”游戏。 The loop is needed to draw the hanger and the parts depending on the right or wrong answer.需要循环来根据正确或错误的答案绘制衣架和零件。 Each function has the code to draw the next step.每个函数都有绘制下一步的代码。 There is an if statement in the loop, if the user answers the wrong letter then function(i) should be used (depending on the amount of times the user has missed).循环中有一个 if 语句,如果用户回答错误的字母,则应使用 function(i)(取决于用户错过的次数)。

Thank you!谢谢!

You can put all of them in a list and call them by index.您可以将它们全部放在一个列表中并按索引调用它们。 Then you don't need to worry about what they are called, just the order that they should be called, which seems to be the most important thing for you.那么你就不必担心它们叫什么,只需要关心它们应该被调用的顺序,这对你来说似乎是最重要的。

def function1():
    print('function 1')


def function2():
    print('function 2')


def function3():
    print('function 3')

functions = [function1, function2, function3]


i = 1

while i <= 3:

    functions[i-1]() #note the () to call the function

    i += 1

您可以使用 eval("function1()") 来运行 function1,这样您就可以在每次 for 循环运行时更改字符串。

First things first: if you could, should you?第一件事:如果可以,应该吗?

Second thing: yes, you can, but probably shouldn't.第二件事:是的,你可以,但可能不应该。

def function1():
    return 1

def function2():
    return 2

# ...

i, num = 1, 2 # num can be as much as you have defined functions
while i < num + 1:
    print(globals()[f'function{i}']())
    i += 1

# out
# 1
# 2

Maybe you should take a look into lambda expressions and globals .也许你应该看看lambda 表达式globals

As stated in @Alon 's answer, you can also you eval .@Alon的回答所述,您也可以eval But keep in mind that both solutions are a result of bad design and I repeat: being able is not a good reason to do it .但请记住,这两种解决方案都是糟糕设计的结果,我再说一遍:能够做到这一点并不是很好的理由

You can assign functions to variables in python.您可以在python中为变量分配函数。 This variable can then be overwritten with another function.然后可以用另一个函数覆盖此变量。 An example of this can be seen here:一个例子可以在这里看到:


def fn1(x):
   return x

def fn2(x):
   return x*2


test = fn1
print(test(4)) # prints 4

test = fn2
print(test(4)) # prints 8

Applying this to your example we can create an array containing all your functions, which you iterate over the indexes or a dictionary where the key is your id and the value is your function:将此应用于您的示例,我们可以创建一个包含所有函数的数组,您可以遍历索引或字典,其中键是您的 id,值是您的函数:

def function1(args):
    do this

def function2(args):
    do that

def function3(args):
    do something

myfunctions = {'1':function1,'2':function2, etc...}

i = 1
while i <= len(myfunctions):
    myfunctions[str(i)](args)
    i += 1

or using the list method:或使用列表方法:

def function1(args):
    do this

def function2(args):
    do that

def function3(args):
    do something

myfunctions = [function1,function2, etc...]

for i in range(myfunctions):
    myfunctions[i](args)

I would say that if you are running all the functions 0:X the list method is simpler, but if you have data telling you which one to run a key-value dictionary would be easier.我会说,如果您运行所有函数 0:X,则列表方法更简单,但是如果您有数据告诉您运行键值字典中的哪个函数会更容易。

In an ideal world, you would have one function that does different things based on its input.在理想的世界中,您将拥有一个根据其输入执行不同操作的函数。

Note on eval As per the other answers, the use of eval would also work, however in the interest of efficiency and good coding practice it is better avoided if possible!关于 eval 的注意事项 根据其他答案,使用 eval 也可以使用,但是为了效率和良好的编码习惯,最好尽可能避免使用!

In your case, when one function follows another, I would do something like this:在你的情况下,当一个函数跟随另一个函数时,我会做这样的事情:

def function1():
    do this
    return function2

def function2():
    do that
    return function3

def function3():
    do something
    return fail?

def...

function = function1
i = 1
while i <= X:
    function = function()
    i += 1

where there is always a function called, but it changes each iteration to the next one.总是有一个function被调用,但它会将每次迭代更改为下一次。

Firstly, I wanted to suggest the same as others with writing functions in lists or dictionaries and iterating through them.首先,我想建议与其他人一样,在列表或字典中编写函数并遍历它们。 But I think returning the next function is better for your case.但我认为返回 next 函数更适合您的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM