i reading post , had question regarding __cmp__().
my code
class book(object): def __init__(self, title, year): self.title = title self.year = year def __hash__(self): # hash function print "self = ", self print "hash value of self = ", hash(str(self)) print "hash value of title = ", hash(self.title) print "hash value of year = ", hash(self.year) return 0 def __cmp__(self, other): return self.title == other.title books = [] books.append(book("abc", 123)) print hash(books[0]) books.append(book("def", 456)) print hash(books[1]) books.append(book("abc", 123)) print hash(books[len(books)-1]) print len(books) print cmp(books[0],books[2]) output
self = <__main__.book object @ 0x0000000001e77b00> hash value of self = -1040857764 hash value of title = 826005955 hash value of year = 123 0 self = <__main__.book object @ 0x0000000001e77ba8> hash value of self = -992414627 hash value of title = -589261154 hash value of year = 456 0 self = <__main__.book object @ 0x0000000001e77be0> hash value of self = 1901105233 hash value of title = -2015893559 hash value of year = 789 0 self = <__main__.book object @ 0x0000000001e77c18> hash value of self = -228580758 hash value of title = 826005955 hash value of year = 123 0 4 1 # how ? == operator on strings returns boolean value.
in code cmp() compares 2 strings (namely titles) return value of cmp() must bool.
- how come getting integer ? (i looking explanation respect comparison of objects
x > y) - even when integer obtained, how value decided ?
- how can make 1st , 3rd object equal ?
how come getting integer ?
__cmp__ returns int. __cmp__ returning bool, subclass of int, python interprets int.
even when integer obtained, how value decided ?
- -1 means first operand less second
- 0 means both operands equal
- +1 means first operand greater second
how can make 1st , 3rd object equal?
the problem code __cmp__ returns result of ==, returns bool, subclass of int, , true 1, instead of returning 0 __cmp__ returning true/1 -- wrong.
the methods should using (as __cmp__ gets removed in later pythons) __eq__, __ne__, __le__, __lt__, __ge__, , __gt__.
using __eq__:
def __eq__(self, other): if not isinstance(other, self.__class__): return notimplemented return self.title == other.title note comparing title, , not considering year (which may fine, or may not be, depending on how using book class).
you can find out more them here.
Comments
Post a Comment