python - 我有一个具有一个必需参数和两个可选参数的类,以及一个返回可选参数之一的 repr 方法,以给定者为准
问题描述
class MyClass():
def __init__(self, name, high=None, low=None):
self.name = name
if low:
self.low = low
elif high:
self.high = high
else:
raise Error("Not found")
def __repr__(self):
value = self.low or self.high
return '{}({}, {})'.format(str(self), self.name, value)
我有一个单元测试用例,其中 MyClass 被实例化,
gain = MyClass('name', high='high_value')
assert isinstance(repr(gain), str)
但是当我的 repr() 被调用时,它会抛出 AttributeError,
AttributeError:“MyClass”没有属性“低”
解决方案
我会将您的代码重构为以下内容
class MyClass:
def __init__(self, name, high=None, low=None):
self.name = name
self.low = low
self.high = high
if self.low is None and self.high is None:
raise Error("Not found")
if self.low is not None and self.high is not None:
raise Error("Only low OR high may be specified, not both")
def __repr__(self):
value = self.low if self.low is not None else self.high
return '{}({}, {})'.format(str(self), self.name, value)
因此,在__init__
您的断言中,恰好设置了低或高之一,换句话说,既没有设置也没有设置两者都是错误的。然后,您可以根据传入的值__repr__
进行分配。在这种情况下,和都将存在,尽管它们的值之一是.value
self.low
self.high
None
推荐阅读
- bootstrap-4 - 覆盖 box-shadow 变量仅适用于 !important 标志
- c# - 在另一个线程中循环 ping + 更新 UI
- jenkins - Signtool 在指定时间服务器的詹金斯构建上失败
- xpath - 如何在 Tibco BW 5 中使用 XPath 格式化数字
- ios - 如何使用 alamofire 将数组数据发送到 api?
- javascript - 如何将这两个功能合二为一?
- java - 如何在 Liquibase 中使用其他表中的列创建索引?
- apache-spark - spark结构化流检查点目录下的子目录
- javascript - 以下哪项决定是否在浏览器中启用 cookie?
- reactjs - TypeError: (node.text || []).map 不是函数