[sage-devel] Customizing hash for an instance of ?

Sat, 10 Sep 2011 01:48:39 -0700

Hi!

I am trying to change the hash function of an instance after it is
created. I tried to override the __hash__ attribute of the instance
with a bound method created from a custom hash function. It worked for
<type 'instance'>, but not for instances of <type 'object'>:

  sage: def my_hash(self):
  ....:     print "custom hash"
  ....:     return id(self)
  ....:
  sage: class Foo:
  ....:     def __hash__(self):
  ....:         print "Foo's hash"
  ....:         return id(self)
  ....:
  sage: class Bar(object):
  ....:     def __hash__(self):
  ....:         print "Bar's hash"
  ....:         return id(self)
  ....:
  sage: f = Foo()
  sage: b = Bar()
  sage: import types
  sage: f.__hash__ = types.MethodType(my_hash, f, Foo)
  sage: b.__hash__ = types.MethodType(my_hash, b, Bar)

Now, f uses the custom hash:

  sage: hash(f)
  custom hash
  93075504

But b is still using the hash function from its class:
  sage: hash(b)
  Bar's hash
  94410128
  sage: type(f)
  <type 'instance'>
  sage: type(b)
  <class '__main__.Bar'>

Experts, please tell me why it doesn't work, and how to work around
(if possible).

Best regards,
Simon

-- 
To post to this group, send an email to sage-devel@googlegroups.com
To unsubscribe from this group, send an email to 
sage-devel+unsubscr...@googlegroups.com
For more options, visit this group at http://groups.google.com/group/sage-devel
URL: http://www.sagemath.org

Reply via email to