通过C++学习Python

2019-10-05 10:24:01王冬梅

而 Python 在 2001 年加了一把力,引入了 Nested Scopes 的技术7:


def adder(amount):
return lambda x: x + amount
...
print(adder(5)(5))

C++11 不甘示弱,整出了 capture-list 的概念8。


auto adder(int amount) {
    return [=](int x){ return x + amount; };
}
...
std::cout << adder(5)(5);

内置算法

Python 里有诸多内置的强大算法函数,如 filter:

result = filter(mylist, lambda x: x >= 0)
C++11 倒也可以用 std::copy_if 干同样的事情:


auto result = std::vector<int>{};
std::copy_if(mylist.begin(), mylist.end(), std::back_inserter(result), [](int x){ return x >= 0; });

这样的函数在 <algorithm> 中屡见不鲜,而且都在与 Python 中的某种功能遥相呼应:transform, any_of, all_of, min, max.

可变参数

Python 从一开始就支持可变参数了。你可以定义一个变参的函数,个数可以不确定,类型也可以不一样。


def foo(*args):
    for x in args:
        print(x);
foo(5, "hello", True)

C++11 里 initializer_list 可以支持同类型个数可变的参数(C++ Primer 5th 6.2.6)。


void foo(std::initializer_list<int> il) {
    for (auto x : il)
        std::cout << x;
}

foo({4, 5, 6});

看到这里,你是否发现用 C++ 学习 Python 也不失为一种很妙的方式呢? 从这个问题的答案,可以看出 @Milo Yip 也是同道中人呢。

继续

觉得不错?想要大展拳脚? 看看这个 repo 吧。上面有更多的方式,教你用 C++ 来学习 Python.