Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

Why a function in a dictionary that passes arguments is executed immediately? [duplicate]

$
0
0

I'm fairly new to Python.

I was creating a script that performed a series of functions.

I don't know how many functions I would have done, so I opted for a menu on which the choices were based on a global dictionary, where the keys represent the user's input choice and the values the call to the associated function.

As seen in the following snippet, within the dictionary, there are several func2 functions.

Initially I treated these functions individually (func2, func3, func4, ...). But I noticed that these repeated themselves following a common basic pattern. So, since I recently covered classes in OOP, I thought I could abstract these functions into a class.

The idea was to associate each choices key with a function to which I would, in the case of func2, pass the 'identifier' argument.

These arguments were already defined as key in another nested dictionary (dict). So, after calling the class constructor and creating a generic object, through the category, I would pass the single nested dictionary (dict:{"CatA" : {sub_dict}, ... }) to the method of that object that would produce a total and this would be printed along with the category it belongs to.

#main.pyfrom menu import *choices = {"1": func1,"2": func2("CategoryA"),"3": func2("CategoryB"), ..."7": func3, ...}def main(): while True:  printMenu()  # the print lines are set up like this: `num) description`  choice = input("Enter choice: ")  if choice == "0":   break  elif choice in choices:   choices[choice]()  else:   print("Invalid Choice")if __name__ == "__main__": main()
# menu.pydef func1(): ...def func2(category: str): from dict import extractDict from classfunc2 import ClassFunc2 dict = extractDict() obj = ClassFunc2() total = obj.totNumber(**dict[category]) obj.printResults(total,category)def func3() ... def printMenu() ...
# classfunc2.pyclass ClassFunc2: def __int__(self):  return def totNumber(self, **dict):  ...  a = input(smth)  ...  return total def printResults(self, total, category):  print()

But here comes the problems:when I run the script, for some reason unknown to me, only all instances of func2 are executed before I can select them from the menu.I'm very sure I did something wrong with the abstraction, but I don't know where at all.

Can someone explain to me why this happens and how should I fix this script?

PS: I know the title isn't accurate, but I didn't know what else to put. I would appreciate it if you could share some ideas on how to improve the title.


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>