Dynamically determine base classes on instantiation

Richard Thomas chardster at gmail.com
Fri Aug 17 07:50:43 EDT 2012


On Thursday, 16 August 2012 19:49:43 UTC+2, Steven D'Aprano  wrote:
> On Thu, 16 Aug 2012 10:03:51 -0700, Richard Thomas wrote:
> 
> 
> 
> > class Foo(object):
> 
> >     def __new__(cls, arg):
> 
> >         if isinstance(arg, list):
> 
> >             cls = FooList
> 
> >         elif isinstance(arg, dict):
> 
> >             cls = FooDict
> 
> >         return object.__new__(cls, arg)
> 
> > 
> 
> > class FooList(Foo, list):
> 
> >     pass
> 
> > 
> 
> > class FooDict(Foo, dict):
> 
> >     pass
> 
> 
> 
> 
> 
> Did you actually try your code?
>  

I rarely test code. I'm confident in, however undeserved the confidence. :) In this case that's not an error I've ever seen before. Obvious easy fix:

return cls.__new__(cls, arg)

Incidentally when I reply to your posts through the groups.google.com interface it inserts a blank quoted line between each pair of lines. My first thought was that it was a line endings bug with Google's app but in retrospect that seems very likely to have been fixed years ago. Any ideas?



More information about the Python-list mailing list