2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

python swigで生成したユーザ定義型のメソッドを上書きする方法

Last updated at Posted at 2013-12-27

swigでpython extensionを生成すると、Cで定義した構造体は自動的に以下のような__repr__が定義される。

<swig_mymodule.mytype; proxy of <Swig Object of type 'struct mytype *' at 0x7f6c74210a20> >

このままだとかっこ悪いのでなんとかしたいが、C側で(というかswigで)制御する方法はみつからなかった。

以下のように%pythoncode内でsetattrしてやればswigが生成するpython code内にその内容が出力されるので、import時に上書きされるようになる

swig_mymodule.i
%pythoncode %{
import types

def __mytype_str(self):
    return "<Mytype(…)>”

setattr(mytype, '__str__', types.MethodType(__mytype_str, None, mytype))
%}
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?