[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

Number::Number(int start) {
data = start; // python print goes to stdout
printf("Number: %d\n", data); // or: cout << "Number: " << data << endl;
}


Number::~Number() {
printf("~Number: %d\n", data);
}


void Number::add(int value) {
data += value;
printf("add %d\n", value);
}


void Number::sub(int value) {
data -= value;
printf("sub %d\n", value);
}


int Number::square() {
return data * data; // if print label, fflush(stdout) or cout << flush
}


void Number::display() {
printf("Number=%d\n", data);
}


So that you can compare languages, the following is how this class is used in a C++
program. Example 20-16 makes a Number object, calls its methods, and fetches and sets
its data attribute directly (C++ distinguishes between “members” and “methods,”
while they’re usually both called “attributes” in Python).


Example 20-16. PP4E\Integrate\Extend\Swig\Shadow\main.cxx


#include "iostream.h"
#include "number.h"


main()
{
Number *num;
int res, val;


num = new Number(1); // make a C++ class instance
num->add(4); // call its methods
num->display();
num->sub(2);
num->display();


res = num->square(); // method return value
cout << "square: " << res << endl;


num->data = 99; // set C++ data member
val = num->data; // fetch C++ data member
cout << "data: " << val << endl;


1504 | Chapter 20: Python/C Integration

Free download pdf