Re: [Pyobjc-dev] Problems opening a panel
Brought to you by:
ronaldoussoren
From: Bob I. <bo...@re...> - 2005-01-31 06:22:59
|
On Jan 31, 2005, at 12:47 AM, Dethe Elza wrote: > I've seen this usage, either on the pyobjc Wiki or maybe the LettErr > wiki: It must've been the LettErr Wiki, because PyObjC doesn't have it's own wiki and I'm not aware of any tasty PyObjC morsels on the pythonmac.org wiki. > class MyClass(NSObject): > > def __new__(cls): > return cls.alloc().init() > def __init__(self): > # do additional initialization here > > my_object = MyClass() > > This seems to work OK and it gives a more pythonic feel when using > classes derived from Cocoa. I can see why it may be an abuse, as it > makes using the derived classes inconsistent with using PyObjC > classes, but perhaps there are better reasons to avoid it that I'm not > aware of. Perhaps this would hose Interface Builder if you tried to > initialize your class in a Nib? > > I use this pattern myself, so I'd like to know in advance if I'm doing > a Bad Thing(tm). If your __new__ is *only* a short-cut to calling the Objective-C allocator and designated initializer, then it is technically sound but I certainly wouldn't recommend it. In most cases, using __new__ confuses people because it is an automatic class method, it appears similar to __init__ but is completely different, is only around for new-style classes, and for these reasons its usage is not very common. If you are trying to make a class act really "Pythonic" you probably should just wrap it with a proxy that acts Pythonic and calls Objective-C stuff underneath (though that is usually more work than it's worth). If you want a shortcut to create instances of your class, make a proper class method in the Objective-C style. It is never ever a good idea to use __init__ because it will not be called from Objective-C. We should probably go as far as to make the class-builder refuse to build classes that implement __init__. Ronald? -bob |