簡體   English   中英

欺騙Python運算符優先級

[英]Spoofing Python operator precedence

我知道當我比較兩個對象lhs == rhs並都定義__eq__ ,只有lhs.__eq__被調用,除非它返回NotImplementedrhslhs的子類。

但是,我想實現一個類,該類的實例在與任意對象進行比較時將有機會說出它們想要說的內容,而與arbitrary_object.__eq__的實現細節以及比較語句中的位置無關。 聽起來有些尷尬,但是我正在研究一個面向測試的項目,請看一下testmania.expect ,您將了解我需要什么。

我最初的想法是使我的類成為使用metaclass magic和__instancecheck____subclasscheck__ subclasscheck__的任何其他類的子類。 但是,如果進行簡單比較,它們根本不會被調用。

有人有什么新主意嗎?

我不知道這是否可以滿足您的需求,但是為什么不測試這兩個操作呢?我的意思是測試是否: object1 == object2object2 == object1並且通常您應該得到相同的值,除非其中一個對象已經重寫了__eq__方法,因此您將執行此新的__eq__方法並返回true,該示例勝於單詞:

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

希望這會有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM