[英]How to test for negative number and raise ValueError?
我正在学习本教程。 我正在迭代地解决这个问题。 此时我有以下 Binary 类:
class Binary:
def __init__(self,value):
self.value = str(value)
if self.value[:2] == '0b':
print('a binary!')
self.value= int(self.value, base=2)
elif self.value[:2] == '0x':
print('a hex!')
self.value= int(self.value, base=16)
else:
print(self.value)
def __int__(self):
if self.value[:1] == '-':
return ValueError
return int(self.value)
我正在使用 pytest 运行一套测试,包括:
def __int__(self):
> if self.value[:1] == '-':
E TypeError: 'int' object is not subscriptable
我理解错误,因为我将参数保存为 int。 在这种情况下,测试负数并引发 valueerror 异常的好策略是什么?
如果value
是 int,则value < 0
是对 value 为负的测试。 你应该已经知道这一点。 也许您应该查看文档集中的教程。
一个单独的问题是您的init方法被混淆了。 它将输入转换为字符串,有时将字符串(返回?)转换为 int。 到init完成时, self.value 应该具有所需类型的允许值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.