整数包装类中的异常测试

时间:2013-08-01 04:06:57

标签: python class integer wrapper equality

假设我在Python中创建了一个整数包装类,就像Java一样。大多数方法都非常简单。但 __ eq __ 重载(相等测试)提出了一个有趣的难题:考虑以下方法

def __eq__( self, other ):
    return self.value == int(other)

实施细节:

  • Integer Wrapper有一个字段“value”,它是一个整数
  • 方法 __ trunc __ 返回字段“value”,以便int(Integer(x))= x
  • Integer的构造函数将“value”截断为整数;整数(3.1)=整数(3)

方法规则

  1. 整数(x)==整数(x)必须对所有整数x
  2. 返回true
  3. 整数(x)== x必须对所有整数x
  4. 返回true
  5. 整数(x)==整数(y)必须为所有的inegers(x,y)返回false,这样x!= y
  6. 整数(x)== y必须为所有x!= y
  7. 返回false

    我漂亮的方法很容易受到最后一次测试的影响。考虑

    Integer(1) == 1.1
    

    将返回true。

    我们如何在规定的约束条件下实现一个Integer类 - 这似乎是微不足道的,具有相当直接的平等定义?

    注意:您可能会觉得很难,我声称Integer(1.1)== Integer(1)是一个有效的结果。我承认它有一些愚蠢,但我可以控制构造函数如何处理非整数参数;如果我想声称不安全的演员,我可以抛出异常。我对第四种情况没有任何控制权,其中有人询问我的整数是否等于相同值的原语。

    修改 根据请求,这里有足够的代码,我认为我已经提出的条件得到满足:

    class Integer:
      """ An integer wrapper class. Provides support for using integers as
          objects. There are subtelties and pitfalls, however. """
    
     def __init__( self, val = 0 ):
        """ Constructs a new integer with a certain value """
        self.val = int(val)
    
     def __trunc__( self ):
     """ Truncates the internal value """
     return int(self.val)
    
     def __eq__( self, other ):
     """ Returns true if the object ahs the same value as this object """
     return self.val == int(other)
    

2 个答案:

答案 0 :(得分:1)

如果我正确地解释了你的要求,那就应该这样做:

>>> class Integer:
...   def __init__(self, val=0):
...     self.val = int(val)
...   def __eq__(self, other):
...     return self.val == other
... 
>>> Integer(1) == 1.1
False
>>> Integer(1.2) == Integer(1.3)
True
>>> Integer(4) == Integer(7)
False
>>> Integer(2) == 2
True
>>> 

答案 1 :(得分:0)

如果我理解正确,那么这里的问题是你比较的值可能是一个浮点数而不是一个int,反过来,如果与之比较,它会被截断为一个相等的int。

如果是这种情况如何检查,如果比较值有一个余数除以比较值并作出反应:

def __eq__( self, other ):
    if float(other) % self.value > 0:
        return False
    else:
        return True

这样你就可以传入一个可以被self.value()整除的浮点数,或者一个整数相同的值,并且对于

的所有情况都返回true

int(x) == y || int(x) == int(y) || int(x) == float(y), for all x / y = 1

相关问题