Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

python - Executing functions within switch dictionary

I have encountered a problem when putting all the modules I've developed into the main program. The switch dictionary I've created can be seen below:

def Tank_Shape_Calcs(Tank_Shape, level, area, dish, radius, length, Strapping_Table, Tank_Number):

    switcher = {
        0: vertical.Vertical_Tank(level, area),
        1: horiz.Horiz_Cylinder_Dished_Ends(dish, radius, level, length),
        2: strapping.Calc_Strapped_Volume(Strapping_Table, level),
        3: poly.Fifth_Poly_Calcs(Tank_Number)
    }
    return switcher.get(Tank_Shape, "ERROR: Tank type not valid")

The tank shape is set in the main file in a loop for each of the tanks. The first tank has Tank_Shape = 2 so I would expect it to execute the Calc_Strapped_Volume() function.

I have tried testing it, and the switcher function is definitely reading Tank_Shape as 2. Also if I change the functions to strings, it will print out the correct string.

The problem is that the functions seem to be executed sequentially, until the correct function is called. This results in errors as the data I'm using will only work with the correct function.

Is there a way to only execute the correct function?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

All your functions are executed when you build the dictionary, not when you access the key.

You need to use lambda (without any parameters, they are already known) to make sure the function is only called when required:

switcher = {
    0: lambda : vertical.Vertical_Tank(level, area),
    1: lambda : horiz.Horiz_Cylinder_Dished_Ends(dish, radius, level, length),
    2: lambda : strapping.Calc_Strapped_Volume(Strapping_Table, level),
    3: lambda : poly.Fifth_Poly_Calcs(Tank_Number)
}

then call when you return, with the error message as a lambda that returns it:

return switcher.get(Tank_Shape, lambda : "ERROR: Tank type not valid")()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...