![]() |
Class Data Members |
![]() |
![]() |
![]() |
データメンバもPythonに開示でき、その結果Pythonクラスに対応する属性でアクセスされ得る。 公開を望むデータメンバはread-onlyかread-writeに注目される。 クラスVarについて考えよう。
struct Var
{
Var(std::string name) : name(name), value() {}
std::string const name;
float value;
};
このC++クラスVarとそのメンバはPythonに開示できる。
class_<Var>("Var", init<std::string>())
.def_readonly("name", &Var::name)
.def_readwrite("value", &Var::value);
Pythonでは
>>> x = Var('pi')
>>> x.value = 3.14
>>> print x.name, 'is around', x.value
pi is around 3.14
valueがread-writeとして公開されるのに対して、 nameはread-onlyとして公開されることに注意しなさい。
>>> x.name = 'e' # can't change name
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: can't set attribute
![]() |
![]() |
![]() |
Copyright © 2002 David Abrahams
Copyright © 2002 Joel de Guzman
Permission to copy, use, modify, sell and distribute this document
is granted provided this copyright notice appears in all copies. This document
is provided "as is" without express or implied warranty, and with
no claim as to its suitability for any purpose.