python – 使用class作为特殊值?
发布时间:2020-12-20 11:30:24 所属栏目:Python 来源:网络整理
导读:在 Python中使用类作为特殊值是否丑陋? 考虑一下: def find_result(): result = None # do something to find the result,even recursing return resultr = find_result()if r is None: raise Exception("we have no result") 如果我希望结果是数字或任何
在
Python中使用类作为特殊值是否丑陋?
考虑一下: def find_result(): result = None # do something to find the result,even recursing return result r = find_result() if r is None: raise Exception("we have no result") 如果我希望结果是数字或任何“正常”类型,这将完美地工作. 但是,如果存在任意数据结构,结果可以是从None到另一个结构的任何内容呢?我在我的案例中所做的是: class NoResult: """i'm even less than `None`.""" pass def query(data,path): result = NoResult # traverse and recurse into the data structure return result r = query() if r is NoResult: raise Exception("our hands are empty") 它有效,但我无法摆脱这种感觉,我有点滥用这里的贫困阶层,甚至可能存在潜伏在里面的真正危险. 这是真的吗?我在上课吗?或者只是我的算法很糟糕,如果它需要依赖这样的“特殊无”? 解决方法
它被称为哨兵,你可以使用任何独特的对象:
sentinel = object() if r is sentinel: raise Exception(..) 这里我使用了一个简单的object()实例而不是自定义类. 自定义类确实具有可能更自我记录的优点;如果您的API必须将对象传递给API的用户(可以是代码),那么显式类更好.仅在API的黑盒子中使用,object()就可以了. 您可能想要考虑在现在返回标记的位置处引发异常.您可以再次捕获异常. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |