此代码是在Python和工作得很好:检查字典中是否存在项目,这是不好的做法吗?
# tests if class exists in the dictionary attrs
try:
self.attrs['class']
# if it doesnt python will throw an exception
except KeyError:
self.attrs['class'] = "someclass"
# else it is defined, so we concat someclass to previous value
else:
self.attrs['class'] = "someclass %s" % self.attrs['class']
虽然,这恐怕不是一个好的做法,因为如果蟒蛇有一个更新,并且改变抛出的异常,它可能会停止工作的名称。这是不好的做法吗?有没有更好的方法来做到这一点?
从我pythonism的理解它实际上不是。你不应该担心名称改变。这会破坏太多的代码,而不是重要的更新,而这些更新都是你知道的。 – 2013-03-06 17:14:29
你可能会发现http://programmers.stackexchange.com/questions/175655/python-forgiveness-vs-permission-and-duck-typing有趣。 – George 2013-03-06 17:27:11