python - 欺骗Python运算符优先级

标签 python operator-overloading metaclass magic-methods

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

但是我想实现一个类,该类的实例在与任意对象进行比较时将有机会说出他们想说的话,无论 arbitrary_object.__eq__ 的实现细节如何并且无论比较语句中的位置如何。听起来有点尴尬,但我正在做一个面向测试的小项目,看看 testmania.expect 你就会知道我需要这个做什么。

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

有人有什么新想法吗?

最佳答案

我不知道这是否适合您的需要,但为什么不测试这两个操作,我的意思是测试:object1 == object2object2 == object1通常你应该得到相同的值,除非其中一个对象覆盖了 __eq__方法,因此您将执行这个新的 __eq__方法并返回 true ,一个例子胜于 Eloquent :

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() 

希望这能有所帮助。

关于python - 欺骗Python运算符优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5290044/

相关文章:

c++ - 通过继承专门化运算符模板

ruby - Class 怎么可能属于 Class 类而没有 Class 实例方法呢?

python - 如何在 Heroku 上正确安装 PyICU?

python - 仅根据条件 python 加入

java - 有没有办法在 Java 中向 GregorianCalendar 添加方法?

python - 可作为实例方法调用?

c++ - 需要帮助将 Graphics32 Delphi 示例转换为 C++

python - 如何使用 python configparser 读取缩进部分

python - PyQt : How to set up a widget hidding an other widget if it's visible?

c++ - 重载 << 运算符以插入到 vector 中