can't rebind magic methods

Michael Tobis mtobis at gmail.com
Sat Mar 18 19:25:58 EST 2006


I'd appreciate an explanation of why this doesn't work and any
workarounds.

It's not a showstopper, but I'd like to pseudo-inherit a bunch of magic
methods from an attribute, and would prefer to abstract the definitions
into a loop rather than write them all out.

thanks
mt


###########
import new

class myint(object):

    def __init__(self,val):
        self.val = int(val)
        def mystr(self):
            return self.val.__str__()
        self.__str__ = new.instancemethod(mystr,self,mint) #doesn't
work

        self.str = new.instancemethod(mystr,self,mint)

    """

    # this works



    def __str__(self):

        return self.val.__str__()

    """

if __name__ == "__main__":
    a = myint(3)
    b = a
    a.val = 42
    print b # want "42"

    print b.str() # works




More information about the Python-list mailing list