Вопрос

EDIT: The following code had a simple mistake which didn't actually illustrate the problem. I've left it here(uncorrected), but I'm still curious about answers to the questions at the bottom.

I have the following object in Python, that is supposed to always return true for an equality test:

class Wildcard(object):
    def __eq__(self, other):
        return True

It works in some cases, but not all:

>>> w = Wildcard()
>>> w == 'g'
True
>>> 'g' == w
True
>>> w == 10
True
>>> 10 == 'w'
False

From my understand, the == operator passes the second operand into the __ eq__ method of the first, which explains why w == 10 works but 10 == w does not. This raises two questions. First, is it possible to construct that object that has this property regardless of which operand it is? Second, why does this work on a string, but not an int? What about String's __ eq__ method makes it evaluate 'g' == w to True?

Это было полезно?

Решение

Unfortunately, there is no way (that I know of) to construct such an object. Consider:

>>> class Wildcard(object):
...     def __eq__(self, other):
...         return True
... 
>>> w = Wildcard()
>>> w == 10
True
>>> 10 == w
True
>>> class Joker(object):
...     def __eq__(self, other):
...         return False
... 
>>> j = Joker()
>>> w == j
True
>>> j == w
False

There is no reason for w (a Wildcard) to take precedence over j (a Joker) in this scenario.


Now, you might be wondering why this works for strings and ints -- It's because if the class's test returns the singleton NotImplemented, then the test is delegated from the first argument to the second:

>>> class Foo(object):
...     def __eq__(self, other):
...         if isinstance(other, Wildcard):
...             return NotImplemented
...         else:
...             return False
... 
>>> f = Foo()
>>> 
>>> f == 1
False
>>> f == Foo()
False
>>> f == w
True

Другие советы

from unittest.mock import ANY

assert ANY == 2
assert 2 == ANY
assert (4, 2) == (ANY, 2)
assert "abc" == ANY
assert ANY == "abc"
assert ANY == False
assert ANY == True
assert ANY == None
assert ANY
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top