【发布时间】:2015-07-23 05:50:47
【问题描述】:
假设我有一个名为 generator 的函数,它返回一个 4 元组,其中包含在某些预先指定的范围内随机选择的值。假设元组的形式为(age, sex, location, marital_status):
age is in range(5, 85)
sex is a member of the set {"m", "f"}
location is a member of the set of all the cities in California
marital_status is a member of {"married", "single", "separated"}
另一方面,假设我已经定义了 20 个不同的函数,其定义如下:
def p1 (age, sex, location, marital_status)
def p2 (age, sex, location, marital_status)
.
.
p1 应该接收具有以下形式的值的参数:
`age` must be in the range 20 to 45
`sex` must be male
`location` could be any city in Southern California
`marital_status` could be either single or married
并想象p2 一直到p20 的一组不同值。
确定哪组生成的值与哪个函数匹配的实用方法是什么?
在这种情况下,所有定义完全相同,但我可以想象定义可能略有不同的情况,例如p18 可能是def p1 (age, location),对@987654332 的可能性范围有特定限制@和location。
附:这些模式不一定是互斥的,这意味着一组生成的值可能会匹配多个函数。
【问题讨论】:
-
由于您使用的是 Python 3,函数注释 可能是要走的路:python.org/dev/peps/pep-3107。
-
模式是互斥的,还是可能有更多的模式匹配?
-
@dlask:好点。模式匹配多个函数的可能性很小。
-
是否可以在 p1-p20 上循环,检查函数本身,如果与 reqs 不匹配则抛出 ValueError 并继续执行下一个函数?避免代码重复。
-
@JLPeyret:听起来很有趣。能否详细解答一下?
标签: python function python-3.x pattern-matching parameter-passing