3 回答

TA贡献1744条经验 获得超4个赞
我认为问题是因为在switcher创建字典时会调用前两个函数。您可以通过lambda如下所示的所有值函数定义来避免这种情况:
def choice(i):
switcher = {
1: lambda: subdomain(host),
2: lambda: reverseLookup(host),
3: lambda: 'two'
}
func = switcher.get(i, lambda: 'Invalid')
print(func())

TA贡献1833条经验 获得超4个赞
有一个选项很明显是正确的..:
def choice(i, host): # you should normally pass all variables used in the function
if i == 1:
print(subdomain(host))
elif i == 2:
print(reverseLookup(host))
elif i == 3:
print('two')
else:
print('Invalid')
如果您使用的是字典,重要的是所有的 rhs(右侧)都具有相同的类型,即采用零参数的函数。当我使用 dict 来模拟 switch 语句时,我更喜欢将 dict 放在使用它的地方:
def choice(i, host):
print({
1: lambda: subdomain(host),
2: lambda: reverseLookup(host),
3: lambda: 'two',
}.get(i, lambda: 'Invalid')()) # note the () at the end, which calls the zero-argument function returned from .get(..)

TA贡献1883条经验 获得超3个赞
可以使用 Python 中的字典映射来实现切换案例,如下所示:
def Choice(i):
switcher = {1: subdomain, 2: reverseLookup}
func = switcher.get(i, 'Invalid')
if func != 'Invalid':
print(func(host))
有一个字典switcher有助于根据函数的输入映射到正确的函数Choice。有要实现的默认情况,使用 完成switcher.get(i, 'Invalid'),因此如果返回'Invalid',您可以向用户提供错误消息或忽略它。
调用是这样的:
Choice(2) # For example
请记住host在调用 之前设置值Choice。
添加回答
举报