[英]How to test for negative number and raise ValueError?
I'm working through this tutorial .我正在学习本教程。 I'm working through this iteratively.
我正在迭代地解决这个问题。 At this point I have the following Binary class:
此时我有以下 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)
I'm running through a suite of tests using pytest, including:我正在使用 pytest 运行一套测试,包括:
def __int__(self):
> if self.value[:1] == '-':
E TypeError: 'int' object is not subscriptable
I understand the error since I saved the parameter as an int.我理解错误,因为我将参数保存为 int。 What is a good strategy to test for a negative number and raise a valueerror exception in this case?
在这种情况下,测试负数并引发 valueerror 异常的好策略是什么?
If value
is an int, then value < 0
is the test that value is negative.如果
value
是 int,则value < 0
是对 value 为负的测试。 You should already know this.你应该已经知道这一点。 Perhaps you should review the tutorial in the doc set.
也许您应该查看文档集中的教程。
A separate problem is that your init method is confused.一个单独的问题是您的init方法被混淆了。 It turns the input into a string and sometimes turns the string (back?) into an int.
它将输入转换为字符串,有时将字符串(返回?)转换为 int。 By the time init is finished, self.value should have an allowed value of the desired type.
到init完成时, self.value 应该具有所需类型的允许值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.