add method to class dynamically?

Neal Becker ndbecker2 at gmail.com
Wed Oct 22 14:29:08 CEST 2008


I have a class (actually implemented in c++ using boost::python).  For an instance of this class, 'r', I'd like to support len (r).  I don't want to add it to the c++ code, because this is a unique situation: this class should not normally support len().

So I try:
r = ring_int (10)
r.__len__ = lambda: 10

This doesn't work:
>>> len(r)
TypeError: object of type 'ring_int' has no len()

It appears that __len__ is being looked up only on the class dict, not the instance dict?  What's the correct way to do this?  (Of course, I could just use inheritance, but this is an opportunity for me to learn more about python)




More information about the Python-list mailing list