Overriding methods per-object

Piet van Oostrum piet at cs.uu.nl
Sat Apr 18 22:01:28 CEST 2009


>>>>> Pavel Panchekha <PavPanchekha at gmail.com> (PP) wrote:

>>> The docs don't say you can do that:
>PP> Thanks, hadn't noticed that.

>>> Should you be able to?

>PP> I'd say so. In my case, I need a class that can encapsulate any
>PP> object, add a few methods to it, and spit something back that works
>PP> just like the object, but also has those extra methods. I can't just
>PP> add the methods, because it has to work on e.g. lists. So I'll have to
>PP> end up defining all the possible methods on that class (and that's
>PP> still not best because I can't use hasattr to test if, for example,
>PP> addition is allowed on that object).

>PP> On the other hand, I see how this severely restricts the possibly
>PP> optimizations that can be made in the interpreter.

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
>>> a.__nonzero__()
False
>>> a.append(4)
>>> a
[1, 2, 3, 4]
>>> 

-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list