add method to class dynamically?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Neal Becker

    add method to class dynamically?

    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)

  • Diez B. Roggisch

    #2
    Re: add method to class dynamically?

    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?

    Diez

    Comment

    • Neal Becker

      #3
      Re: add method to class dynamically?

      Diez B. Roggisch wrote:
      BTW, could you stop setting the followup-to to a non-existing (at least
      for a standard newsreader) gmane-newsgroup?
      >
      Is this any better?

      Comment

      • Diez B. Roggisch

        #4
        Re: add method to class dynamically?

        Neal Becker wrote:
        Diez B. Roggisch wrote:
        >
        >BTW, could you stop setting the followup-to to a non-existing (at least
        >for a standard newsreader) gmane-newsgroup?
        >>
        >
        Is this any better?
        Yes, thanks.

        Diez

        Comment

        Working...