Overriding methods in classes you don't control

Amaury Forgeot d'Arc afa.NOSPAM at neuf.fr
Wed Mar 30 04:20:21 CEST 2005

Alex VanderWoude a écrit :
> Here's the situation.  I'm using wxPython, and I want to make an enhancement
> in the __init__ method of all the frame classes. The ideal place to do this
> is in wxFrame.__init__, since any change there will automatically be
> inherited by the other frame classes (for example, wxMDIParentFrame).
> Obviously I can inherit from wxPython and make the changes in my subclass,
> but then I would have to also subclass wxMDIParentFrame and duplicate my
> enhancements there, and then use only my subclasses rather than the wx***
> classes.
> Basically I want to change wxFrame.__init__ so that it looks sort of like
> this:
>     def __init__(self, *args, **kwargs):
>         # Some enhancements here.
>         # The original code of this method, including the call to its
> ancestor.
>         # Some more enhancements here.
> And then I can replace wxFrame's __init__ with my new version by assigning
> it before any frames are instantiated.

Sorry, but this won't work with wxPython.
wxPython classes are just wrappers around C++ classes.

You may well replace wxFrame.__init__ with your own method, but it won't
be called by wxMDIParentFrame: wxMDIParentFrame.__init__ directly calls
the C++ constructor, completely ignoring wxFrame.__init__.
The call to the superclass' constructor is done in C++.

Since replacing C++ method is much more difficult (if possible at all),
I'm afraid you will have to do the replacement you plan for every
derived class.


More information about the Python-list mailing list