Re: [Pyobjc-dev] Mixin classes
Brought to you by:
ronaldoussoren
From: Ronald O. <ron...@ma...> - 2009-05-08 05:42:39
|
On 8 May, 2009, at 1:46, Greg Ewing wrote: > Ronald Oussoren wrote: > >> Mixins cannot be used to add new methods that the ObjC runtime >> will see. > > In PyGUI I'm using the following metaclass to get a > similar effect to multiple inheritance. It merges the > class dicts of all the base classes before creating > the class. > > Usage example: > > class PyGUI_NSWindow(NSWindow, PyGUI_NS_EventHandler): > __metaclass__ = NSMultiClass > ... > > The first base class should be an ObjC class; the > rest can be ordinary Python classes. > > Note that this implementation results in methods in > later base classes overriding those in earlier ones, > which is more or less the opposite of what normally > happens. If you use this technique, you might want > to reverse the order of the merging. Wouldn't it be more useful to tweak NSMulticlass to do the updates of the class dict in the right order? Ronald > > #-------------------------------------------------- > > from inspect import getmro > > def NSMultiClass(name, bases, dic): > # Workaround for PyObjC classes not supporting > # multiple inheritance properly. Note: MRO is > # right to left across the bases. > main = bases[0] > dic2 = {} That is: for mix in bases[::-1]: > for mix in bases[1:]: > for cls in getmro(mix)[::-1]: > dic2.update(cls.__dict__) # drop the next line: > dic2.update(dic) > cls = type(main)(name, (main,), dic2) > return cls > > #-------------------------------------------------- > > -- > Greg |