Overriding methods per-object

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sun Apr 19 03:00:33 CEST 2009


En Sat, 18 Apr 2009 19:39:24 -0300, Pavel Panchekha  
<PavPanchekha at gmail.com> escribió:
> On Apr 18, 4:01 pm, Piet van Oostrum <p... at cs.uu.nl> wrote:

>> But you can give each object its own class and then put the special
>> methods in that class:
>>
>> >>> def create_special_object(bases, *args):
>>
>> ...   if not isinstance(bases, tuple):
>> ...      bases = bases,
>> ...   cls = type("SpecialClass", bases, {})
>> ...   return cls(*args)
>> ...>>> a = create_special_object(list, [1,2,3])
>> >>> a
>> [1, 2, 3]
>> >>> a.__class__
>>
>> <class '__main__.SpecialClass'>
>>
>> >>> a.__class__.__nonzero__ = lambda self: False
>> >>> bool(a)
>> False
>
> I think this is the solution I like best.

You may want to implement some kind of cache: creating a new class for  
every instance is expensive.
Also, note that those instances are not pickleable.

-- 
Gabriel Genellina




More information about the Python-list mailing list