Ken
Ken

Reputation: 1471

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.

Upvotes: 1

Views: 366

Answers (2)

Klaus D.
Klaus D.

Reputation: 14369

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.

Upvotes: 2

xana
xana

Reputation: 499

When you create dictionary, first these methods are called = thats why you see something twice, then values which are returned from methods are assigned to dict (in this case None, cause methods only prints, nothing returned).

Upvotes: 1

Related Questions