Python中如何仅为满足条件的对象定义属性,访问不符条件时报错
Python条件属性定义与自定义错误抛出实现
我们需要实现如下需求:仅为满足指定条件的类对象开放对应属性,当不满足条件的对象访问该属性时,直接抛出自定义的业务错误,而非默认的模糊报错。
原始实现及存在的问题
原始代码实现如下:
class Polynomial: def __init__(self, number_of_variables:int): self.number_of_variables = number_of_variables if self.is_univariate(): self.nroots = compute_number_of_roots(self) # 该函数返回多项式的根数量 def is_univariate(self): return self.number_of_variables == 1 def number_of_roots(self): if self.is_univariate(): return compute_number_of_roots(self) # 该函数返回多项式的根数量 else: raise Exception("Number of roots is not defined for multivariate polynomials.")
该实现的问题在于:当我们定义多变量多项式实例p = Polynomial(3)后,调用p.number_of_roots()可以抛出符合预期的自定义错误,但直接访问属性p.nroots时,只会触发Python默认的AttributeError: 'Polynomial' object has no attribute 'nroots'错误,提示信息十分模糊,无法直观体现业务层面的不支持原因。
正确实现方案
通过Python的@property装饰器将对应属性改为计算属性即可解决该问题,实现代码如下:
class Polynomial: def __init__(self, number_of_variables:int): self.number_of_variables = number_of_variables def is_univariate(self): return self.number_of_variables == 1 @property def nroots(self): if self.is_univariate(): return compute_number_of_roots(self) # 该函数返回多项式的根数量 else: raise Exception("Number of roots is not defined for multivariate polynomials.")
该方案下,无论多项式是否为单变量,访问nroots属性都会先执行自定义的条件校验逻辑:符合单变量条件时返回根数量计算结果,不符合时直接抛出业务层面的自定义错误,不会再出现模糊的默认属性不存在报错。
内容的提问来源于stack exchange,提问作者Tereso del Río Almajano
相关产品推荐
相关产品推荐

