![]() |
Class Data Members |
![]() |
![]() |
![]() |
Data members may also be exposed to Python so that they can be accessed as attributes of the corresponding Python class. Each data member that we wish to be exposed may be regarded as read-only or read-write. Consider this class Var:
struct Var
{
Var(std::string name) : name(name), value() {}
std::string const name;
float value;
};
Our C++ Var class and its data members can be exposed to Python:
class_<Var>("Var", init<std::string>())
.def_readonly("name", &Var::name)
.def_readwrite("value", &Var::value);
Then, in Python:
>>> x = Var('pi')
>>> x.value = 3.14
>>> print x.name, 'is around', x.value
pi is around 3.14
Note that name is exposed as read-only while value is exposed as read-write.
>>> 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.