简体   繁体   English

使用.get()python通过函数传递参数

[英]Pass parameters through function with .get() python

I have the following code 我有以下代码

    cmd = raw_input("> ")
    if cmd[0] == "/":
        if " " in cmd:
            cmd = cmd.split(" ")
            {
            '/help':  help,
            '/cf':  cf(f = cmd[1]),
            '/rf':  rf(f = cmd[1]),
            '/md':  md(f = cmd[1]), 
            '/rd':  rd(f = cmd[1]), 
            '/dir': dir(f = cmd[1]), 
            '/tree': tree(f = cmd[1]), 
            '/date': date, 
            '/time': time_, 
            '/clear': clear,
            '/echo': echo(f = cmd[1]),   
            }.get(cmd[0])()

For some reason, if I call, say, /md, it runs it as if I called /cf, can anyone offer any insight? 出于某种原因,如果我叫/ md,它将像我叫/ cf一样运行,有人可以提供任何见解吗?

My whole code can be found here: https://pastebin.com/ukwY6LfV 我的整个代码可以在这里找到: https : //pastebin.com/ukwY6LfV

Without looking more deeply into your code, I can tell you that your structure looks odd... Looking at the second line in your dict, '/cf': cf(f = cmd[1]), you're calling the func cf() there, and then potentially calling it again at the end with the }.get(cmd[0])() at the end. 无需更深入地研究您的代码,我可以告诉您您的结构看起来很奇怪...看一下字典的第二行, '/cf': cf(f = cmd[1]),您正在调用函数cf(),然后可能在末尾再次使用}.get(cmd[0])()再次调用它。 I see that you're trying to set f as the parameter, too. 我看到您也在尝试将f设置为参数。 But I don't think you want to be calling the func in the first instance. 但是我不认为您想一开始就调用func。 Rather you just want the "pointer" to the func, the func name. 相反,您只希望功能的“指针”即功能名称。 Since you're trying to pass an arg, I think the lambda statement is what you want. 由于您尝试传递arg,因此我认为lambda语句是您想要的。 So, try changing: 因此,尝试更改:

'/cf':  cf(f = cmd[1]),

to

'/cf':  lambda p=cmd[1]: cf(f = p),

and see if that does the trick. 看看是否能解决问题。 With the lambda call, you're not actually calling the cf() func, but rather you're creating a new, nameless function that IS going to later call the cf() func with the desired parameter, if invoked. 通过lambda调用,您实际上并没有在调用cf()函数,而是在创建一个新的无名函数,该函数稍后将调用带有所需参数(如果被调用)的cf()函数。

Your lines for /date, /time, and /clear should be okay, but you will need to change all the other lines inside your "dict" statement to use the lambda call. 您的/ date,/ time和/ clear行应该可以,但是您需要更改“ dict”语句中的所有其他行以使用lambda调用。

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

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