classobj() question
Peter Otten
__peter__ at web.de
Tue Feb 12 11:20:01 EST 2008
Roland Hedberg wrote:
> I'm in the position that I have a bunch of classes defined before hand
> and then in some special circumstances I need to dynamically create a
> class that has a number of the static classes as parents.
>
> So I thought I could use classobj() from the new module, it seem exactly
> what I wanted.
>
> But, it doesn't perform as I expected.
>
> I've made an extremely simple program to try to show what I mean and
> what I expected. It's attached to this mail.
>
> So, how should I have done it ?
(1) You are working with newstyle classes -- use type() instead of
new.classobj().
(2) Your inheritance tree has diamonds in it -- call baseclass initializers
using super() in *all* classes, e. g:
class A(object):
def __init__(self):
super(A, self).__init__()
# your code
Python will then take care that every initializer in the inheritance tree is
called once.
(3) You can explore the order in which the initializers are called by
printing the classes' __mro__ attribute for the final tweaks.
See
http://www.python.org/download/releases/2.2.2/descrintro/#mro
for an introduction to newstyle multiple inheritance and
http://www.python.org/download/releases/2.3/mro/
if you want to dig deeper or like ascii art ;)
Peter
More information about the Python-list
mailing list