<pre><code> But I noticed how people also raised objections,
that checking for types betrays a "not object oriented" design
</code></pre>
<p>实际上,它被称为<a href="http://en.wikipedia.org/wiki/Duck_typing#In_Python" rel="nofollow">Duck typing style</a>(“如果它看起来像鸭子,并且嘎嘎叫起来像鸭子,那么它一定是鸭子。”),而且python语言推荐使用这种编程风格。在</p>
<p>在duck输入时,会有一些东西叫<a href="http://docs.python.org/glossary.html#term-eafp" rel="nofollow">EAFP</a>(请求原谅比允许更容易)</p>
^{pr2}$
<p>你的意思是更多的Python,基本上在你的情况下,更多的Python是这样的:</p>
<pre><code>def myfunc(val):
cmd_type = 'i'
# forget about passing type to your magicprogram
cmdline = 'magicprogram %s ' % val
Popen(cmdline, ... blah blah)
</code></pre>
<p>在你的魔法程序里(我不知道是你的剧本还是…),因为
在所有的情况下,你的程序都会得到一个字符串,所以试着把它转换成
脚本接受</p>
<pre><code>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
</code></pre>
<p>我不知道你的代码都是什么,但是你可以按照上面的例子来做,它更像Python,记住每个规则都有例外,所以也许你的例子就是个例外
你最好做类型检查。在</p>
<p>希望这能为你澄清一切。在</p>