Replace Whole Object Through Object Method
Bruno Desthuilliers
onurb at xiludom.gro
Mon Jun 26 14:31:00 EDT 2006
digitalorganics at gmail.com wrote:
> Maric Michaud wrote:
>
(snip)
>>This doesn't work in most cases (with new style classes), better recreat a
>>type which inherit from Class and Mixin, or Class.__dict__ with
>>Mixin.__dict__.
>
>
> What doesn't work exactly? The whole purpose of the mixin is to add
> functionality to the class and hence to all its instances on the fly.
very naïve solution:
def mixin(obj):
def someFunc(self, ...)
# code here
def someOtherFunc(self, ...)
# code here
cls = obj.__class__
cls.someFunc = someFunc
cls.someOtherFunc = someOtherFunc
Just a bit less nïave solution:
def mixin(func):
func._mixin = True
return func
def mixable(func):
return getattr(attr, '_mixin', False):
class Mixin(object):
@mixin
def someFunc(self, ...):
# code here
@mixin
def someOtherFunc(self, ...)
# code here
def mix(cls, mixincls):
for name in dir(mixincls):
attr = getattr(mixincls, name)
if callable(attr) and mixable(attr):
setattr(cls, name, attr)
Of course, one can do much better...
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"
More information about the Python-list
mailing list