Python的方式有2-3个选项的选择作为参数传递给函数 [英] Pythonic way to have a choice of 2-3 options as an argument to a function

查看:139
本文介绍了Python的方式有2-3个选项的选择作为参数传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这需要大量的参数,其中之一是模拟的执行类型Python函数。例如,选项可能是太阳,查看或并重。

I have a Python function which requires a number of parameters, one of which is the type of simulation to perform. For example, the options could be "solar", "view" or "both.

这是一个Python化的方式来允许用户设置这些?

What is a Pythonic way to allow the user to set these?

我可以看到各种选项:


  1. 使用一个字符串变量,并检查它 - 所以这将是 FUNC(A,B,C,键入='太阳')

设置在类的一些常量和使用 FUNC(A,B,C,键入= classname.SOLAR)

Set some constants in the class and use func(a, b, c, type=classname.SOLAR)

如果只有两个选项(因为有一些在我的职务),迫使它变成一个真/假的说法,使用类似 FUNC(A,B,C,do_solar = FALSE)来得到它使用视图选项。

If there are only two options (as there are for some of my functions) force it into a True/False argument, by using something like func(a, b, c, do_solar=False) to get it to use the 'view' option.

任何preferences(或其他想法),这样做的Python化的方式?

Any preferences (or other ideas) for Pythonic ways of doing this?

推荐答案

我不喜欢任何这些选项。

I don't like any of those options.

我定义了两个不同的功能, perform_solar(A,B,C) perform_view(A,B,C),让来电者决定他要用哪些,以什么顺序,并与其中的参数。

I'd define two different functions, perform_solar(a, b, c) and perform_view(a, b, c) and let the caller decide which ones he wants to use, in which order and with which arguments.

如果你为什么认为你不得不打包到这些单一功能的原因是,他们共享状态,你应该共享状态的对象,定义功能的方法。

If the reason why you thought you'd have to pack these into one single function is that they share state, you should share that state in an object and define the functions as methods.

这篇关于Python的方式有2-3个选项的选择作为参数传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆