代码之家  ›  专栏  ›  技术社区  ›  gcstr

从Objective-C调用Python

  •  7
  • gcstr  · 技术社区  · 17 年前

    • 如何从Objective-C调用Python方法?
    • 我的Python类正在Interface Builder中实例化。如何从该实例调用方法?
    1 回复  |  直到 17 年前
        1
  •  16
  •   bbum    13 年前

    使用PyObjC。

    >>> from Foundation import *
    >>> a = NSArray.arrayWithObjects_("a", "b", "c", None)
    >>> a
    (
          a,
          b,
          c
    )
    >>> a[1]
    'b'
    >>> a.objectAtIndex_(1)
    'b'
    >>> type(a)
    <objective-c class NSCFArray at 0x7fff708bc178>
    

    它甚至可以与iPython配合使用:

    In [1]: from Foundation import *
    
    In [2]: a = NSBundle.allFrameworks()
    
    In [3]: ?a
    Type:       NSCFArray
    Base Class: <objective-c class NSCFArray at 0x1002adf40>
    

    `

    要从Objective-C调用Python,最简单的方法是:

    • 在类的@implementation中创建方法的存根实现

    • 在Python中对类进行子类化,并提供具体的实现

    即。

    @interface Abstract : NSObject
    - (unsigned int) foo: (NSString *) aBar;
    + newConcrete;
    @end
    
    @implementation Abstract
    - (unsigned int) foo: (NSString *) aBar { return 42; }
    + newConcrete { return [[NSClassFromString(@"MyConcrete") new] autorelease]; }
    @end
    
    .....
    
    class Concrete(Abstract):
        def foo_(self, s): return s.length()
    
    .....
    
    x = [Abstract newFoo];
    [x  foo: @"bar"];