Confused about bound functions
Alex Martelli
aleaxit at yahoo.com
Sat Aug 18 13:50:33 EDT 2001
"Theodore D. Sternberg" <strnbrg at c532352-a.frmt1.sfba.home.com> wrote in
message news:20xf7.12187$P15.6890321 at news1.rdc1.sfba.home.com...
> Why do I need to pass in a self argument, in the
> last line of the following program?
Because c.foo is a function, not a method.
> class C:
> pass
>
> c = C()
> cmd = 'def foo(self): print "I am foo"'
> exec cmd in c.__dict__
>
> c.foo(c)
> ------------------------
>
> I'd like to be able to say simply "c.foo()".
> How can I arrange for that?
You need to exec cmd in C.__dict__ -- the
dictionary of c's class. If you want to make
sure that other instances of C remain
unaffected, you need to arrange for c to
get its own class, e.g in today's Python:
def addmethod(obj, defstring):
class Local(obj.__class__): pass
obj.__class__ = Local
exec defstring in Local.__dict__
There are alternatives based on module new.
Alex
More information about the Python-list
mailing list