Mix-In Class Methods At Run-Time
bearophileHUGS at lycos.com
bearophileHUGS at lycos.com
Sat Jun 24 20:02:47 EDT 2006
I think it's possible, most of such kind of things are possible with
Python.
I'm not an expert yet in such kind of things, so this can be a starting
point for you (note the shadowing of m2, the class docstrings, etc).
Other people can give you something better or more correct.
class A:
def m1(self): return "m1"
def m2(self): return "m2"
class B:
def m3(self): return "m3"
class P:
def m2(self): return "m2b"
def m4(self): return"m4"
def mixin(object, *classes):
class NewClass(object.__class__):
pass
for C in classes:
NewClass.__dict__.update(C.__dict__)
object.__class__ = NewClass
foo = P()
print "Before:"
print "foo.__class__.__dict__.keys():", foo.__class__.__dict__.keys()
print "P.__dict__.keys():", P.__dict__.keys()
print "foo.m2():", foo.m2()
print "foo.m4():", foo.m4(), "\n"
mixin(foo, A, B)
print "After:"
print "foo.__class__.__dict__.keys():", foo.__class__.__dict__.keys()
print "P.__dict__.keys():", P.__dict__.keys()
print "foo.m1():", foo.m1()
print "foo.m2():", foo.m2()
print "foo.m3():", foo.m3()
print "foo.m4():", foo.m4()
Bye,
bearophile
More information about the Python-list
mailing list