Re: [Pyobjc-dev] Accessing python classes in obj-c
Brought to you by:
ronaldoussoren
From: b.bum <bb...@ma...> - 2003-12-08 21:10:02
|
On Dec 8, 2003, at 12:17 PM, Jiva DeVoe wrote: > So I understand that I can create Python files and the templates > supplied with PyObjC automatically will load those Python files and do > what ever I want them to. I also understand if I instantiate a python > class in python, and access it in obj-c, I will get a proxy object to > the python object. However, what if I have an objective-c > application, and I want to write a portion of it in python. So, in > other words, I want to be able to create a class in Python, and > instantiate an object in objective-c that is of that class. How would > I do that? Would I have to use something like SWIG? No SWIG necessary. If you subclass an Objective-C class from Python, the resulting class will look/feel/work just like any other Objective-C class. To ensure that selector mapping-- method mapping-- works correctly, you will need to make sure that method's in the Python implementation are correctly named (i.e. -setObject:forKey: is setObject_forKey_ and not setObjectForKey ). Because Python is a "lazily linked" interpreted language, you have to ensure that any classes you want to use have been defined before they are used. This causes two issues; runtime and compile time. Runtime is easy -- just make sure you import the class in Python before it is used. Compile time is a bit harder. In particular, you can't refer to any class implemented in python directly because there won't be a real class object to link against as the source is compiled. To solve this problem, I have used an abstract superclass implemented in Objective-C (a class that simply declares all the methods where the implementation is stubbed out) and a concrete subclass implemented in Python. To the abstract superclass-- the objc class-- I have added a factory method that instantiates and returns the concrete subclass. This is effectively exactly how class clusters work. Finally, you have to trigger the execution of a bit of python code from somewhere in your code for all of this to work. The easiest solution would be to simply grab the main() function that uses/initializes the embedded interpreter and use that within your app. Then your main.py could import whatever classes you need to start the application and you could go from there. b.bum |