python - No implied relationship among the comparison operators -


i started reading the python language reference, release 2.7.10.

in section 3.4: special method names , particularly regarding comparison operators object.__eq__(self, other) , object.__ne__(self, other) states following has lead confusion:

there no implied relationships among comparison operators. truth of x==y not imply x!=y false. accordingly, when defining eq(), 1 should define ne() operators behave expected.


what statement mean? how can truth of x==y not automatically , without question translate false value of x!=y?

"no implied relationships" means when use "!=", if haven't implemented __ne__, it's not going instead call __eq__ , negate result. use __ne__ method inherited parent. of time, resolve object.__ne__ checks referential equality.

>>> class fred: ...     def __eq__(self, other): ...         print "eq called!" ...         return false ... >>> x = fred() >>> print x == 23 eq called! false >>> #if eq , ne had implied relationship,  >>> #we'd expect next line print "eq called!" >>> print x != 23 true >>> #... doesn't. 

it means you're free define __eq__ , __ne__ in ways seem mathematically contradictory. python won't hold hand.

>>> class fred: ...     def __eq__(self, other): ...         return true ...     def __ne__(self, other): ...         return true ... >>> x = fred() >>> print x == 23 true >>> print x != 23 true 

although suggest should implement them in mathematically sensible way. above code block legal, not wise.


Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -