| Class Properties

In C++, classes with public data members are usually frowned upon. Well designed classes that take advantage of encapsulation hide the class' data members. The only way to access the class' data is through access (getter/setter) functions. Access functions expose class properties. Here's an example:

`

        struct Num
        {
            Num();
            float get() const;
            void set(float value);
            ...
        };

`

However, in Python attribute access is fine; it doesn't neccessarily break encapsulation to let users handle attributes directly, because the attributes can just be a different syntax for a method call. Wrapping our `Num` class using Boost.Python:

`

        class_<Num>("Num")
            .add_property("rovalue", &Var::get)
            .add_property("value", &Var::get, &Var::set);

`

And at last, in Python:

`

        >>> x = Num()
        >>> x.value = 3.14
        >>> x.value, x.rovalue
        (3.14, 3.14)
        >>> x.rovalue = 2.17 #error!

`

Take note that the class property `rovalue` is exposed as read-only since the `rovalue` setter member function is not passed in:

`

        .add_property("rovalue", &Var::get)

`

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.