简体   繁体   English

Python 函数字典调用每个函数

[英]Python dictionary of functions calls every function

This seems very trivial but for some reason my dictionary is not working.这看起来很微不足道,但由于某种原因,我的字典不起作用。

This is the code I have:这是我的代码:

class Calculator():
    def __init__(self):
        number = input()
        self.switch_case(number)

    def switch_case(self, number):
        switcher = {
            1: self.one(),
            2: self.two(),
        }

    def one(self):
        print("something")

    def two(self):
        print("something")

For some reason this calls both functions one() and two() even when I only enter the value 1 as an input.出于某种原因,即使我只输入值 1 作为输入,这也会调用 one() 和 two() 函数。

Actually it calls nothing.实际上它什么也不叫。 Your code as presented is never run.您提供的代码永远不会运行。

But if you would create a Calculator instance, __init__ is run which then runs switch_case and initializes the dictionary by evaluating the value expressions.但是,如果您要创建一个Calculator实例,则会运行__init__ ,然后运行switch_case并通过计算值表达式来初始化字典。 This will call both functions.这将调用这两个函数。

If you don't want to run them at this point, remove the parentheses:如果此时不想运行它们,请删除括号:

switcher = {
        1: self.one,
        2: self.two,
        }

and call the function when needed, with something like:并在需要时调用该函数,例如:

self.switcher[1]()

Note the () which will do the call.注意()将执行调用。

当您创建字典,第一,这些方法被称为=这就是为什么你看到的东西两次,然后值被从方法返回被分配到字典(在这种情况下没有,原因仅方法打印,没有返回)。

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

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