欺骗Python运算符优先级

时间:2011-03-13 14:38:15

标签: python operator-overloading metaclass magic-methods

我知道当我比较两个对象lhs == rhs并定义__eq__时,只调用lhs.__eq__,除非它返回NotImplementedrhs是子类lhs

但是我想实现一个类,其中的实例与任意对象相比,将有机会说出他们想说的内容,无论arbitrary_object.__eq__的实现细节如何,无论在比较语句中的位置如何。这听起来很尴尬,但我正在开展一个面向测试的项目,看看testmania.expect,你就会明白我需要的是什么。

我最初的想法是让我的类成为使用元类魔法和__instancecheck____subclasscheck__的任何其他类的子类。但是在简单比较的情况下,他们根本就不会被调用。

有人有什么新鲜的想法吗?

1 个答案:

答案 0 :(得分:1)

我不知道这是否符合你的需求,但为什么不测试这两个操作我的意思是测试:object1 == object2object2 == object1通常你应该得到相同的值除非其中一个对象覆盖了__eq__方法,所以你将执行这个新的__eq__方法并返回一个真的,一个例子比单词更好:

def _assert_just_now(first, second):
    """A Dump function to simulate if two dates are almost equal.

    N.B: In this Dump function i will just test if the two datetime object have the
    same hour

    """ 

    from datetime import datetime
    assert isinstance(first, datetime) and isinstance(second, datetime), \
           "This function only accept datetime objects"

    return first.hour == second.hour

class Expectation(object):

     def __init__(self, assertion, first):
         self.assertion = assertion
         self.first = first

     def __eq__(self, other):
         return self.assertion(self.first, other)

def assert_equal(first, second):
   """Usage :

   >>> from datetime import datetime
   >>> t1 = datetime(year=2007, hour=1, month=3, day=12)
   >>> t2 = datetime(year=2011, hour=1, month=5, day=12)

   Without using Expectation it's False.
   >>> assert_equal(t1, t2)
   False

   Use the Expectation object.
   >>> assert_equal(t1, Expectation(_assert_just_now, t2))
   True

   Can use Expectation in the first argument too.
   >>> assert_equal(Expectation(_assert_just_now, t2), t1)
   True

   Work also in Container object.
   >>> assert_equal({'a': 1, 'b': Expectation(_assert_just_now, t2)},
   ...              {'a': 1, 'b': t1})
   True

   We change a little bit the values to make the assert equal fail.
   >>> t3 = datetime(year=2011, hour=2, month=5, day=12)
   >>> assert_equal(t1, t3)
   False

   This just to make sure that the _assert_just_now doesn't accept object 
   other than datetime:
   >>> assert_equal(t1, Expectation(_assert_just_now, "str"))
   Traceback (most recent call last):
       ...
   AssertionError: This function only accept datetime objects

   """

   return first == second or second == first

if __name__ == '__main__':
   import doctest
   doctest.testmod() 

希望这可以提供帮助。