代码之家  ›  专栏  ›  技术社区  ›  James Emerton

python:在类外部定义构造函数

  •  5
  • James Emerton  · 技术社区  · 16 年前

    给出一个类:

    class TCurrency {
        TCurrency();
        TCurrency(long);
        TCurrency(const std::string);
        ...
    };
    

    包裹着Boost.python:

    class_<TCurrency>( "TCurrency" )
        .def( init<long> )
        .def( init<const std::string&> )
        ...
        ;
    

    是否可以创建在python中显示为构造函数的工厂方法:

    TCurrency TCurrency_from_Foo( const Foo& ) { return TCurrency(); }
    

    在python中:

    bar = TCurrency(foo)
    
    2 回复  |  直到 16 年前
        1
  •  12
  •   Bruno Oliveira    16 年前

    你可以使用 make_constructor (未经测试):

    TCurrency* TCurrency_from_Foo( const Foo& ) { return new TCurrency(); }
    
    class_<TCurrency>( "TCurrency" )
        .def( "__init__", boost::python::make_constructor( &TCurrency_from_Foo) )
    ;
    

    生成构造函数的参数是返回包装类的指针[1]的任何函数。

    [1]实际上,函数必须返回指针固定器类型,因此如果指针固定器是 boost::shared_ptr ,函数应返回Boost::Shared_ptr而不是原始指针。

        2
  •  0
  •   Sergey Miryanov    16 年前

    可能是 my example 帮助您-init_python_对象函数可以接受您需要的任何参数。简单说明:我用定义类 boost::noncopyable and no_init .

    推荐文章