But I noticed how people also raised objections,
that checking for types betrays a "not object oriented" design
其实它叫鸭子打字风格(“如果它看起来像鸭子,叫起来像鸭子,那一定是鸭子。”),是python语言推荐使用这种编程风格。
随着鸭子打字的出现,称为EAFP(请求宽恕比许可更容易)
presumable more "more object oriented" way of handling this without
explicitly checking for type?
你的意思是更多的pythonic,基本上在你的情况下更多的pythonic是这样的:
def myfunc(val):
cmd_type = 'i'
# forget about passing type to your magicprogram
cmdline = 'magicprogram %s ' % val
Popen(cmdline, ... blah blah)
在你的魔法程序中(我不知道它是你的脚本还是......),因为在所有情况下你的程序都会得到一个字符串,所以只需尝试将它转换为你的脚本接受的任何内容;
from optparse import OptionParser
# ....
if __name__ == '__main__':
parser = OptionParser(usage="blah blah")
# ...
(options, args) = parser.parse_args()
# Here you apply the EAFP with all type accepted.
try:
# call the function that will deal with if arg is string
# remember duck typing.
except ... :
# You can continue here
我不知道你所有的代码是什么,但你可以按照上面的例子,它更 Pythonic,并记住每条规则都有它们的例外,所以也许你的情况是一个例外,你最好进行类型检查。
希望这会为您解决问题。