add method to class dynamically?

Diez B. Roggisch deets at
Wed Oct 22 14:36:42 CEST 2008

Neal Becker wrote:

> 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)

Yes, they are only looked up on the class. Unfortunately, I don't find the
paragraph in the language-ref that says so.

BTW, could you stop setting the followup-to to a non-existing (at least for
a standard newsreader) gmane-newsgroup?


More information about the Python-list mailing list