add method to class dynamically?

N

Neal Becker

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

Diez B. Roggisch

Neal said:
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:
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?

Diez
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top