我认为 pythonic 的方式不是让对象处于这样一种状态,即尽管处于错误状态,方法调用也不会崩溃。这些是最难发现的错误,因为程序最终崩溃的地方并不是错误发生的地方。
例如。
class PseudoTuple(object):
"""
The sum method of PseudoTuple will raise an AttributeError if either x or y have
not been set
"""
def setX(self, x):
self.x = x
def setY(self, y):
self.y = y
def sum(self):
"""
In the documentation it should be made clear that x and y need to have been set
for sum to work properly
"""
return self.x + self.y
class AnotherPseudoTuple(PseudoTuple):
"""
For AnotherPseudoTuple sum will now raise a TypeError if x and y have not been
properly set
"""
def __init__(self, x=None, y=None):
self.x = x
self.y = y
不应该做的是
class BadPseudoTuple(PseudoTuple):
"""
In BadPseudoTuple -1 is used to indicate an invalid state
"""
def __init__(self, x=-1, y=-1):
self.x = x
self.y = y
def sum(self):
if self.x == -1 or self.y == -1:
raise SomeException("BadPseudoTuple in invalid state")
else:
return self.x + self.y
我认为这属于pythonic的座右铭:
请求宽恕比获得许可更容易
如果异常状态是可以预期在正常执行过程中发生的事情,而不是由于滥用类而导致的用户错误,那么您应该创建自己的异常似乎是合理的。StopIteration 和迭代器就是一个例子。