can't rebind magic methods
Michael Tobis
mtobis at gmail.com
Mon Mar 20 18:48:17 EST 2006
Still a bit confused actually. Any explanation of the following?
mt
####
def getf(method,name):
def f(self, *a, **k): return method(self.val, *a, **k)
f.func_name = name
return f
class myint(object):
def __init__(self, val):
self.val = int(val)
for spec in 'str repr hash hex oct pow add'.split():
name = '__%s__' % spec
method = getattr(int, name)
# comment this out to get the non-working case
setattr(myint,name,getf(method,name)) # works
# uncomment three lines to get the non-working case
# raises TypeError: "expected 1 arguments, got 0" at method
invocation
# why isn't this equivalent to the setattr above?
# def f(self, *a, **k): return method(self.val, *a, **k)
# f.func_name = name
# setattr(myint,name,f) # doesn't work
if __name__ == "__main__":
a = myint(42)
print a
print oct(a)
More information about the Python-list
mailing list