Overriding methods per-object

Pavel Panchekha PavPanchekha at gmail.com
Sat Apr 18 18:39:24 EDT 2009


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
> >>> a.__nonzero__()
> False
> >>> a.append(4)
> >>> a
> [1, 2, 3, 4]
>
> --
> Piet van Oostrum <p... at cs.uu.nl>
> URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4]
> Private email: p... at vanoostrum.org

I think this is the solution I like best.

> FYI this works as you expect if GeneralTypeOfObject is an old-style
> class (i.e. does not inherit from object). If this feature is so more
> important than all those that come with new-style classes, you have
> control over the involved classes and don't care about Python 3.x
> (where old-style classes are gone), you may choose to downgrade
> GeneralTypeOfObject to old-style.

It is important, but new-style classes are important too. And I care
quite a bit about Python 3.x, thus the fact that I prefer the above
solution.



More information about the Python-list mailing list