Python Forum
Dynamically create functions from Json
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dynamically create functions from Json
#3
the best way to create a command driven execution is to use a dictionary, here's a simple example:
class SoftwareCommands:
    def __init__(self):
        self.commands = {
            'func_a': self.func_a,
            'func_b': self.func_b,
            'willy nilly': self.willy_nilly
        }
    
    def func_a(self):
        print("\nHi, I'm func_a")
    
    def func_b(self):
        print("\nHi, I'm func_b")
    
    def willy_nilly(self):
        n = 0
        while n < 10:
            print('n: {}'.format(n))
            n += 1


def main():
    command = None
    sc = SoftwareCommands()
    while command != 'quit':
        command = input("Enter a command, quit to end: ").strip().lower()
        if command in sc.commands:
            sc.commands[command]()

if __name__ == '__main__':
    main()
outout:
Output:
Enter a command, quit to end: func_a Hi, I'm func_a Enter a command, quit to end: willy nilly n: 0 n: 1 n: 2 n: 3 n: 4 n: 5 n: 6 n: 7 n: 8 n: 9 Enter a command, quit to end: quit
Reply


Messages In This Thread
RE: Dynamically create functions from Json - by Larz60+ - Feb-20-2019, 10:27 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Create variable and list dynamically quest_ 12 4,512 Jan-26-2021, 07:14 PM
Last Post: quest_
  Combine Two Recursive Functions To Create One Recursive Selection Sort Function Jeremy7 12 7,520 Jan-17-2021, 03:02 AM
Last Post: Jeremy7
  JSON Decode error when using API to create dataframe Rubstiano7 4 3,001 Jan-11-2021, 07:52 PM
Last Post: buran
  How to create a basic grid with functions trousers1 2 1,869 Nov-22-2019, 04:16 PM
Last Post: ThomasL
  Create a new list dynamically floatingshed 6 14,325 Nov-20-2017, 01:25 PM
Last Post: floatingshed
  dynamically create a list wfsteadman 0 2,382 Aug-30-2017, 05:34 PM
Last Post: wfsteadman

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020