In C ++, key words can be used to declare related members of classes as different attributes. However, in Python, it depends on the naming method of class-related attributes. The following article describes how to embed Python into the member attributes of classes in C ++.
Embedding Python into the member attributes of C ++ classes
In C ++, key words can be used to declare related members of classes as different attributes. However, in Python, it depends on the naming method of class-related attributes. You can use Boost. Python to pass the attributes of class members in C ++ to Python. The following code uses Boost. Python to process attributes of class members. Change the code in BOOST_PYTHON_MODULE to the following.
- BOOST_PYTHON_MODULE(Message)
- {
- class_<Message>("Message", init<std::string>())
- .def("set", &Message::set)
- .def("get", &Message::get)
- .def_readwrite("msg", &Message::msg);
- ;
- }
Set msg, a member of the Message class, to read/write. You can also set it to read-only by using ". def_readonly. For private members in the class, you can also use ". add_property" to set its operation function to an attribute in the Python class. The following code uses ". add_property" to operate private members.
- BOOST_PYTHON_MODULE(Message)
- {
- class_<Message>("Message",init<std::string>())
- .add_property("msg",&Message::get,&Message::set);
- }
The following code uses the compiled Message module in Python.
- >>> import Message
- >>> s = Message.Message('hi')
- >>> s.msg
- 'hi'
- >>> s.msg = 'boot'
- >>> s.msg
- 'boot'
4. class inheritance
The inheritance relationships of classes in C ++ can also be reflected in the Python module through Boost. Python. The following code imports the parent class and subclass into the Python module respectively. The following describes the member attributes of classes embedded in C ++ in Python.
- #include <string.h>
- #include <iostream.h>
- #include <boost/python.hpp>
- using namespace boost::python;
- #pragma comment(lib, "boost_python.lib")
- class Message
- {
- public:
- std::string msg;
- Message(std::string m)
- {
- mmsg = m;
- }
- void set(std::string m)
- {
- mmsg = m;
- }
- std::string get()
- {
- return msg;
- }
- };
- class Msg:public Message
- {
- public:
- int count;
- Msg(std::string m):Message(m)
- {
- }
- void setcount(int n)
- {
- count = n;
- }
- int getcount()
- {
- return count;
- }
- };
- BOOST_PYTHON_MODULE(Message)
- {
- class_<Message>("Message",init<std::string>())
- .add_property("msg",&Message::get,&Message::set);
- class_<Msg, bases<Message> >("Msg",init<std::string>())
- .def("setcount", &Msg::setcount)
- .def("getcount", &Msg::getcount);
The above is an introduction to the member attributes of the class embedded in C ++ in Python. I hope you will gain some benefits.