创建例外的最佳做法是什么?我刚看到这个,我不知道我是否应该感到恐惧或喜欢它.我在书中多次阅读异常永远不会持有字符串,因为字符串本身可以抛出异常.这有什么真相吗?
基本上我从脚本的理解是这样做,所以所有内部Python库将有一个共同的错误消息格式(迫切需要的东西)所以我可以理解为什么把错误消息字符串是一个好主意.(几乎每种方法都会抛出异常,因为完全不需要无效的通过).
有问题的代码如下:
"""
Base Exception, Error
"""
class Error(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return "[ERROR] %s\n" % str(self.message)
def log(self):
ret = "%s" % str(self.message)
if(hasattr(self, "reason")):
return "".join([ret, "\n==> %s" % str(self.reason)])
return ret
class PCSException(Error):
def __init__(self, message, reason = None):
self.message = message
self.reason = reason
def __str__(self):
ret = "[PCS_ERROR] %s\n" % str(self.message)
if(self.reason != None):
ret += "[REASON] %s\n" % str(self.reason)
return ret
Run Code Online (Sandbox Code Playgroud)
这只是冰山一角,但有人可以给我一些洞察力,这是一个什么使这个可怕的想法?或者,如果有一个更好的异常编码过程/风格.
这是一些Ruby代码:
class Duck
def help
puts "Quaaaaaack!"
end
end
class Person
def help
puts "Heeeelp!"
end
end
def InTheForest x
x.help
end
donald = Duck.new
john = Person.new
print "Donald in the forest: "
InTheForest donald
print "John in the forest: "
InTheForest john
Run Code Online (Sandbox Code Playgroud)
而且,我把它翻译成Python:
import sys
class Duck:
def help():
print("Quaaaaaack!")
class Person:
def help():
print("Heeeelp!")
def InTheForest(x):
x.help()
donald = Duck()
john = Person()
sys.stdout.write("Donald in the forest: ")
InTheForest(donald)
sys.stdout.write("John in the forest: ")
InTheForest(john)
Run Code Online (Sandbox Code Playgroud)
结果是一样的.这是否意味着我的Python代码使用duck-typing?我找不到一个鸭子打字的例子,所以我想在Python中可能没有鸭子打字.维基百科中有代码 …