gpt4 book ai didi

python - 长 elif 链与带有 exec() 的字典

转载 作者:行者123 更新时间:2023-12-01 04:09:59 25 4
gpt4 key购买 nike

我是Python新手,我已经阅读了很多关于如何正确编码的教程。不断出现的一件事是永远不要多次编写同一行代码。我不确定长 elif 参数是否有效,但对我来说,它看起来像是糟糕的代码。

例如:

class answers(object):
def __init__(self):
self.x = 'hello world'

def knight(self):
print('Neee!')
def bunny(self):
print('Rawwww!')
def pesant(self):
print('Witch!')
def dingo(self):
print('Bad, wicked, naughty Zoot!')
foo = answers()
egg = input("Sounds:")

if egg == "knight":
foo.knight()
elif egg == 'bunny':
foo.bunny()
elif egg == 'pesant':
foo.pesant()
elif egg == 'dingo':
foo.dingo()
else:
print("I don't know?")

这可行,但我认为下面的代码看起来更干净。

class answers(object):
def __init__(self):
self.x = 'hello world'

def knight(self):
print('Neee!')
def bunny(self):
print('Rawwww!')
def pesant(self):
print('Witch!')
def dingo(self):
print('Bad, wicked, naughty Zoot!')

foo = answers()
responce = {'knight': 'foo.knight()', 'bunny': 'foo.bunny()', 'pesant': 'foo.pesant()', 'dingo': 'foo.dingo()'}

while True:
try:
egg = input('sounds:')
exec(responce[egg])
except KeyError:
print("I don't know")

两行代码都做同样的事情,我使用哪一行真的很重要,或者哪一行比另一行更好?

旁注,我知道通常不应该使用 exec(),但我找不到另一种方法将函数分配给字符串。

最佳答案

如果跳过()和参数,您可以将函数名称分配给变量

responce = {
'knight': foo.knight,
'bunny': foo.bunny,
'pesant': foo.pesant,
'dingo': foo.dingo,
}

然后您可以使用 () (带有预期参数)运行它

responce[egg]()

#responce[egg](arg1, arg2, ...) # if function require arguments

完整代码

class Answers(object): # CamelCase name for class - see PEP8 document

def __init__(self):
self.x = 'hello world'

def knight(self):
print('Neee!')

def bunny(self):
print('Rawwww!')

def pesant(self):
print('Witch!')

def dingo(self):
print('Bad, wicked, naughty Zoot!')

foo = Answers()

responce = {
'knight': foo.knight,
'bunny': foo.bunny,
'pesant': foo.pesant,
'dingo': foo.dingo,
}

while True:
try:
egg = input('sounds:')
responce[egg]() # call function
except KeyError:
print("I don't know")
<小时/>

顺便说一句:这样您甚至可以使用函数名称作为另一个函数的参数。

在 Tkinter 中用于将功能分配给按钮

Button( ..., text="knight", command=foo.knight)

或将函数分配给事件

bind('<Button-1>', foo.knight)
<小时/>

如果您需要为函数分配参数,那么您可以使用lambda函数。

Python3 版本:

responce = {
'knight': lambda:print('Neee!'),
'bunny': lambda:print('Rawwww!'),
'pesant': lambda:print('Witch!'),
'dingo': lambda:print('Bad, wicked, naughty Zoot!'),
}

Python2 版本:

Python2 中的

print 不是函数,因此 lambda 无法与 print 一起使用 - 因此您必须创建函数。

def show(text):
print text

responce = {
'knight': lambda:show('Neee!'),
'bunny': lambda:show('Rawwww!'),
'pesant': lambda:show('Witch!'),
'dingo': lambda:show('Bad, wicked, naughty Zoot!'),
}
<小时/>

编辑:但是我会在没有字典中的函数的情况下执行此操作:)

# --- classes ---

class Answers(object):

def __init__(self):

# TODO: read it from file CSV or JSON
#
# import json
#
# with open("data.json") as f:
# self.data = json.load(f)

self.data = {
'knight': 'Neee!',
'bunny': 'Rawwww!',
'pesant': 'Witch!',
'dingo': 'Bad, wicked, naughty Zoot!',
}

def response(self, text):
try:
return self.data[text]
except KeyError:
return "I don't know"

# --- functions ---

# empty

# --- main ---

foo = Answers()

while True:

egg = input('sounds: ').lower()

if egg == 'exit':
break

print(foo.response(egg))

# ---

print("Good Bye!")

关于python - 长 elif 链与带有 exec() 的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35077320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com