- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是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/
我正在尝试设置 rbenv: https://github.com/sstephenson/rbenv#section_2 我有一个问题:我必须在一切之前使用 rbenv exec 所以现在我要做 b
我已经使用我们的应用程序创建了图像,运行该图像后,我可以看到还创建了 docker 容器,当我尝试进入 docker 容器时,出现以下错误,请您在这里帮助我。 """"OCI runtime exec
这post on javapapers.com显示如何运行 JMH通过键入 mvn exec:exec 在 Maven 中进行基准测试。在 Maven 中运行 JMH 非常方便,因为您可以轻松地从 E
因为我是 shell 脚本的新手,exec命令总是让我感到困惑,同时用 while 探索这个话题循环触发了以下 4 个问题: 下面的语法 1 和 2 有什么区别 语法 1: while read LI
湖一看这两条线 案例 1 set cvsUpdStr [exec cvs -qn upd] 案例 2 set cvsUpdStr [exec cvs -qn upd >&@stdout] 对于第一种情
我有一个配置为使用 Maven 构建和运行的项目。该项目取决于平台特定的 native 库,我正在使用发现的策略 here管理这些依赖项。 本质上,特定平台的 .dll 或 .so 文件被打包到 ja
我发现 tcl exec 命令首先从标准输出返回字符串,然后是标准错误。例如,我下面的“测试脚本”按以下顺序生成消息: puts "test started" puts stderr "some no
我有 rpc error: code = 13 desc = invalid header field value "oci runtime error: exec failed: cannot ex
过去 2 天我遇到了一个问题。 我正在运行一个 tcl 脚本(用于 eggdrop),该脚本在被触发时执行本地 shell 命令(子进程),如果命令成功,它会输出结果。但是,如果命令不成功,我会收到错
假设我有一个像这样的 TCL 脚本: exec ls -l 现在这将打印出当前目录的内容。我需要将该输出作为字符串并解析它。我怎么能做到这一点? 最佳答案 exec返回输出,因此只需为其设置一个变量:
我正在尝试在 PHP 中使用 GNUPLOT 绘制正弦图,但是当我使用 exec 绘制该图时出现此错误: Warning: exec() [function.exec]: Cannot execute
我正在尝试 mvn exec:exec (或 mvn exec:java )使用类路径中的本地 jar 运行我的程序。但是 jar 无法加载: Exception in thread "main" j
我在最新的 Docker CLI 文档中注意到 Docker CLI 命令列表已经扩展。 如果我使用 码头执行 早些时候在容器内启动可执行文件现在我也可以使用 docker 容器执行 命令。 dock
这个问题在这里已经有了答案: Call to a member function exec() on a non-object error in PHP [duplicate] (1 个回答) 关闭
手册页说“exec() 系列函数用新的过程镜像替换当前的过程镜像。”但我不太明白“用新过程图像替换当前过程图像”的含义。比如exec成功,perror就达不到 execl("/bin/ls", /*
手册页说“exec() 系列函数用新的过程镜像替换当前的过程镜像。”但我不太明白“用新过程图像替换当前过程图像”的含义。比如exec成功,perror就达不到 execl("/bin/ls", /*
我正在 UrbanCode Deploy Shell 步骤中执行以下命令。我想要的是针对找到的所有文件运行 Util.sh。 find . -type f -exec ls -al {} \; fin
仅当将“-p”添加到 org.codehaus.mojo:exec-maven-plugin:1.6.0:exec 插件时,以下 pom.xml 执行才会失败,删除此参数后它运行正常,但我需要争论,有
我正在尝试进入 Maven 并开始编写一个小型库。作为库代码的一部分,我想要一个小型演示 Java 应用程序,可以用来查看库在做什么以及如何使用它。现在真正让我烦恼的一件事是,为了执行该演示,我必须执
我是 maven 的新手,在通过 maven 运行类文件时遇到问题 它运行良好 mvn exec:java -Dexec.mainClass="com.test.Test" 但不是 mvn exec:
我是一名优秀的程序员,十分优秀!