6

我有一个类似于以下的类:

class A {
    vector<double> v;
    double& x(int i) { return v[2*i]; }
    double& y(int i) { return v[2*i+1]; }
    double x(int i) const { return v[2*i]; }
    double y(int i) const { return v[2*i+1]; }
}

我想让以下 Python 代码工作:

a = A()
a.x[0] = 4
print a.x[0]

我在想__setattr__and __getattr__,但不确定它是否有效。另一种方法是实现以下 Python:

a = A()
a['x', 0] = 4
print a['x', 0]

不如前一个好,但可能更容易实现(使用__slice__?)。

PS。我正在使用 sip 进行绑定。

谢谢。

4

1 回答 1

8

可以使用__getattr__和自定义%MethodCode;但是,有几点需要考虑:

  • 需要创建一个中间类型/对象,a.x并返回一个提供__getitem__和的对象__setitem__。这两种方法都应该在发生越界时引发IndexError,因为这是用于迭代的旧协议的一部分 via __getitem__; 没有它,迭代时会发生崩溃a.x
  • 为了保证向量的生命周期,a.x对象需要维护对拥有向量的对象的引用(a)。考虑以下代码:

    a = A()
    x = a.x
    a = None # If 'x' has a reference to 'a.v' and not 'a', then it may have a
             # dangling reference, as 'a' is refcounted by python, and 'a.v' is
             # not refcounted.
    
  • 编写%MethodCode可能很困难,尤其是在错误情况下必须管理引用计数时。它需要了解 python C API 和 SIP。

对于替代解决方案,请考虑:

  • 设计 python 绑定以提供功能。
  • 在 python 中设计类以提供使用绑定的 pythonic 接口。

虽然该方法有一些缺点,例如代码被分成更多可能需要与库一起分发的文件,但它确实提供了一些主要好处:

  • 在 python 中实现 pythonic 接口比在 C 或互操作性库的接口中容易得多。
  • 对切​​片、迭代器等的支持可以在 python 中更自然地实现,而不必通过 C API 进行管理。
  • 可以利用 python 的垃圾收集器来管理底层内存的生命周期。
  • pythonic 接口与任何用于提供 python 和 C++ 之间的互操作性的实现分离。有了更扁平和更简单的绑定接口,在 Boost.Python 和 SIP 等实现之间进行更改变得更加容易。

这是演示此方法的演练。首先,我们从基础A类开始。在这个例子中,我提供了一个构造函数来设置一些初始数据。

a.hpp

#ifndef A_HPP
#define A_HPP

#include <vector>

class A
{
  std::vector< double > v;
public:
  A() { for ( int i = 0; i < 6; ++i ) v.push_back( i ); }
  double& x( int i )         { return v[2*i];       }
  double  x( int i ) const   { return v[2*i];       }
  double& y( int i )         { return v[2*i+1];     }
  double  y( int i ) const   { return v[2*i+1];     }
  std::size_t size() const   { return v.size() / 2; }
};

#endif  // A_HPP

在进行绑定之前,让我们检查一下A接口。虽然它在 C++ 中是一个易于使用的接口,但在 python 中存在一些困难:

  • Python 不支持重载方法,当参数类型/计数相同时,支持重载的惯用语将失败。
  • 对双精度(Python 中的浮点数)的引用的概念在两种语言之间是不同的。在 Python 中,float 是不可变类型,所以它的值不能改变。例如,在 Python 中,该语句n = a.x[0]绑定n到引用 floata.x[0]. 赋值n = 4重新绑定n以引用int(4)对象;它没有设置a.x[0]4
  • __len__期望int,不是std::size_t

让我们创建一个有助于简化绑定的基本中间类。

pya.hpp

#ifndef PYA_HPP
#define PYA_HPP

#include "a.hpp"

struct PyA: A
{
  double get_x( int i )           { return x( i ); }
  void   set_x( int i, double v ) { x( i ) = v;    }
  double get_y( int i )           { return y( i ); }
  void   set_y( int i, double v ) { y( i ) = v;    }
  int    length()                 { return size(); }
};

#endif // PYA_HPP

伟大的! PyA现在提供不返回引用的成员函数,并且长度作为int. 它不是最好的接口,绑定被设计为提供所需的功能,而不是所需的接口

A现在,让我们编写一些简单的绑定来在cexample模块中创建类。

这是 SIP 中的绑定:

%Module cexample

class PyA /PyName=A/
{
%TypeHeaderCode
#include "pya.hpp"
%End
public:
  double get_x( int );
  void set_x( int, double );
  double get_y( int );
  void set_y( int, double );
  int __len__();
  %MethodCode
    sipRes = sipCpp->length();
  %End
};

或者,如果您更喜欢 Boost.Python:

#include "pya.hpp"
#include <boost/python.hpp>

BOOST_PYTHON_MODULE(cexample)
{
  using namespace boost::python;
  class_< PyA >( "A" )
    .def( "get_x",   &PyA::get_x  )
    .def( "set_x",   &PyA::set_x  )
    .def( "get_y",   &PyA::get_y  )
    .def( "set_y",   &PyA::set_y  )
    .def( "__len__", &PyA::length )
    ;
}

由于PyA中间类,两个绑定都相当简单。此外,这种方法需要较少的 SIP 和 Python C API 知识,因为它需要较少的%MethodCode块内代码。

最后,创建example.py将提供所需的 pythonic 接口:

class A:
    class __Helper:
        def __init__( self, data, getter, setter ):
            self.__data   = data
            self.__getter = getter
            self.__setter = setter

        def __getitem__( self, index ):
            if len( self ) <= index:
                raise IndexError( "index out of range" )
            return self.__getter( index )

        def __setitem__( self, index, value ):
            if len( self ) <= index:
                raise IndexError( "index out of range" )
            self.__setter( index, value )

        def __len__( self ):
            return len( self.__data )

    def __init__( self ):
        import cexample
        a = cexample.A()
        self.x = A.__Helper( a, a.get_x, a.set_x )
        self.y = A.__Helper( a, a.get_y, a.set_y )

最后,绑定提供了我们需要的功能,python 创建了我们想要的接口。可以让绑定提供接口;但是,这可能需要对两种语言之间的差异和绑定实现有深入的了解。

>>> 从示例导入 A
>>> a = A()
>>> 对于 x in ax:
... 打印 x
...
0.0
2.0
4.0
>>> 斧头[0] = 4
>>> 对于 x in ax:
... 打印 x
...
4.0
2.0
4.0
>>> x = 斧头
>>> a = 无
>>> 打印 x[0]
4.0
于 2012-07-13T14:07:33.447 回答