Pythonic switch in the classroom

I am trying to build switch logic in python.

Substitution Based for the switch statement in Python? I am creating the following code:

def func(string):
    print(string)

class Switch:
    def __init__(self):
        pass

    def first_switch(self, case):
        return {
             '1': func('I am case 1'),
             '2': func('I am case 2'),
             '3': func('I am case 3'),
             }.get(case, func('default'))


switch = Switch()
switch.first_switch('2')

This will give me the result:

I am case 1
I am case 2
I am case 3
default

I expected the output to be

I am case 2

Is this case-logic dictionary applicable only outside the class definition, or am I missing some additional code? It appears that all dictionary key pairs are evaluated when the function is called.

+4
source share
2 answers

You always call all these functions when building a dictionary. This has nothing to do with classes.

d = {'foo': bar()}

bar , d['foo']. , switch; , switch.

, :

arg = {
    '1': 'I am case 1',
    '2': 'I am case 2',
    '3': 'I am case 3',
}.get(case, 'default')
func(arg)

, , , :

{'1': lambda: func('I am case 1'), ...}.get(...)()
                    # call the function you got ^^

, :

from functools import partial

{'1': partial(func, 'I am case 1'), ...}.get(...)()
+7

:

def func(string):
    print(string)

class Switch:
    def __init__(self):
        pass

    def first_switch(self, case):
        param = {
             '1': (func, 'I am case 1'),
             '2': (func, 'I am case 2'),
             '3': (func, 'I am case 3'),
             }.get(case, (func, 'default'))
        return param[0](*param[1:])

switch = Switch()
switch.first_switch('2')
0

Source: https://habr.com/ru/post/1688077/


All Articles