版权声明:本文为博主原创文章,欢迎转载(请声明出处),私信通知即可 https://blog.csdn.net/xinqingwuji/article/details/89184292
数据成员也可以暴露给Python,以便可以将它们作为相应Python类的属性进行访问。我们希望公开的每个数据成员可以被视为只读或读写。考虑这个类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中,假设我们将Var类放在命名空间hello中,就像我们之前做的那样:
>>> x = hello.Var('pi')
>>> x.value = 3.14
>>> print x.name, 'is around', x.value
pi is around 3.14
请注意,名称以只读方式公开,而值以读写方式公开。
>>> x.name = 'e' # can't change name
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: can't set attribute