Play with classes

Peter Otten __peter__ at web.de
Thu Feb 26 06:50:56 EST 2004


Zunbeltz Izaola wrote:

> Hi to all!
> 
> I wonder if it possible (i'm sure python can do :-) ) to define classes on
> runtime. My problem (schematically) is the folowwin.
> 
> The User can choise betwenn 3 property of an object.
> 
> Mode, Type and Subtype.
> 
> I have the following classes defined
> 
> ModeA, ModeB, TypeA, TypeB, TypeC, SubtypeA, SubtypeB.
> 
> Supose the user whant to combine ModeA with TypeB and SubtypeB, so I need
> something like
> 
> class UserClass(ModeA, TypeB, SubtypeB):
>         pass
> 
> I can define all the posibilitys different classes and the using nested
> if/else I can use the correct class, but I want to know if there is a way
> generate in the fly and in this way there is no necesarity to change code
> whe new Modes or Types are created.
> 
> I hope it is clear enough :-)
> 
> Thanks in advance
> 
> Zunbeltz

How about assigning to __bases__?

>>> class A:
...     def alpha(self): print "alpha"
...
>>> class B:
...     def beta(self): print "beta"
...
>>> class C: pass
...
>>> C.__bases__
()
>>> C.__bases__ = (A,B)
>>> c = C()
>>> c.alpha()
alpha
>>> c.beta()
beta
>>>

Trying the same thing with newstyle class resulted in a TypeError:

>>> E.__bases__ = (A, B)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: __bases__ assignment: 'A' deallocator differs from 'object'

Peter




More information about the Python-list mailing list