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.
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. 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.
当您创建字典,第一,这些方法被称为=这就是为什么你看到的东西两次,然后值被从方法返回被分配到字典(在这种情况下没有,原因仅方法打印,没有返回)。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.