在下面的代码中,我使用 assert
是否合理?如果出现任何问题,当我尝试访问属性时无论如何都会发生错误。另一方面,断言提供了描述性错误消息。
你认为我应该保留这个断言吗?
class WeakBoundMethod:
def __init__(self, meth):
assert (hasattr(meth, '__func__') and hasattr(meth, '__self__')),\
'Object is not a bound method.'
self._self = weakref.ref(meth.__self__)
self._func = meth.__func__
最佳答案
assert
不是用于输入验证,而是用于查找您构建代码的假设中的缺陷。它是一个调试和文档工具,但可以禁用。如果您想提供良好的错误消息,请raise TypeError("Object is not abound method")
- 这就是它的用途。
关于Pythonic 处理此错误情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7298412/