Sunday, January 26, 2003


PyObjC continues to evolve rapidly. Yesterday, the ability to add method implementations-- from Python or Objective-C-- to existing Objective-C classes was implemented.

The following example instantiates an instance of NSObject (Objective-C class), invokes the -description method, creates a subclass of NSObject called Foo that implements two methods, adds the two methods from Foo to NSObject, and invokes the two methods via the instance that was created before Foo was created.

And, yes, all of this would work from Objective-C. For example, I could implement custom NSButton drawing methods and use classAddMethods() to add the new functionality to NSButton.

>>> from Foundation import *
>>> anInstance = NSObject.new()
>>> anInstance.description()
'<NSObject: 0x14f310>'
>>> anInstance.respondsToSelector_("doSomethingWithThis:")
0
>>> class Foo(NSObject):
... def description(self): return "<bar>"
... def doSomethingWithThis_(self, obj):
... return '%s and that' % obj
...
>>> import objc
>>> objc.classAddMethods(NSObject, [Foo.description, Foo.doSomethingWithThis_])
>>> anInstance.description()
''
>>> anInstance.doSomethingWithThis_("<This>")
'<This> and that'
>>>

12:39:54 PM  pontificate