我为什么建议前端将Python 作为第二语言?

  • 2019 年 11 月 27 日
  • 筆記

前言

“如何摆脱不停切图的困局?”

这不是一篇制造焦虑的文章,而是充满真诚建议的Python推广文。

当谈论到编程入门语言时,大多数都会推荐PythonJavaScript

实际上,两种语言在方方面面都非常强大。

而如今我们熟知的ES6语言,很多语法都是借鉴Python的。

有一种说法是 “能用 js 实现的,最后一定都会用 js 实现。”

那么这里可以说:“能跟python长得像的,最后一定会像python。”

1. PythonES6语法差别

1. 基本类型

值得注意的是,尽管两者都是弱类型,但python连接时并不会自动转换类型。

// JavaScript  let coerced = 1;  let concatenated = coerced + 'string';
// Python  not_coerced = 1  concatenated = not_coerced + 'string'

直接报错:TypeError: cannot concatenate 'str' and 'int' objects

只有提前把num转换为字符串类型才能正确运行

# Python  not_coerced = 1  concatenated = str(not_coerced) + 'string'

2. Functions ormethods?

JavaScriptPython中,函数和条件的结构极为相似。例如:

// JavaScript  function drSeuss(catInTheHat, thing1, thing2) {    if (catInTheHat == true &&      thing1 == true &&      thing2 == true) {      console.log('is cray');    } else if (catInTheHat != true) {      console.log('boring');    } else {      console.log('so boring');    }  }
# Python  def dr_seuss(cat_in_the_hat, thing1, thing2):    if cat_in_the_hat == True and      thing2 == True and      thing2 == True:      print 'is cray'    elif cat_in_the_hat != True:      print 'boring'    else:      print 'so boring'

但在JavaScript中,“methods”的通俗定义是指语言规范中内置的方法,例如:Function.prototype.apply()

MDN上有对二者的解释:

在大多数方面,Functionsmethods相同,但有两个主要区别:

  • methods可以被隐式传递到调用该methods的对象上。
  • methods能够对类中包含的数据进行操作。

然鹅,在JavaScript中,“类”只是语法糖的存在,稍后我们再进行对比。

3. 模板字符串

在模板字符串上,JavaScript之前是领先于python的。

// JavaScript  let exclamation = 'Whoa!';  let sentence = `They are really similar to Python.`;    console.log(`Template Literals: ${exclamation} ${sentence}`);
# python  print '打印: {} {}'.format('Whoa.', 'Quite!')  # 打印: Yup. Quite!

{}充当占位符。这种语法被诟病颇多,于是在后来的Python3.6版本中,又提供了一种字符串格式化语法——f-strings

直接对比:

name = "Tom"  age = 3  print(f"他叫 {name}, {age} 岁")  # "他叫Tom, 3 岁"

4. 参数默认值

JavaScript再次完美“借鉴”Python:

// JavaScript  function nom(food="ice cream") {    console.log(`Time to eat ${food}`);  }    nom();// Time to eat ice cream
# Python  def nom(food="ice cream"):    print 'Time to eat {}'.format(food)    nom() # Time to eat ice cream

5. 其余参数和* args

Rest参数语法,使我们可以将不定数量的参数表示为数组,传入函数中。

  • Python中,它们称为* args
  • JavaScript...xxx就表示为其余参数。
// JavaScript  function joke(question, ...phrases) {    console.log(question);    for (let i = 0; i > phrases.length; i++) {      console.log(phrases[i]);    }  }    let es6Joke = "Why does JS single out one parameter?"  joke(es6Joke, "Because it doesn't", 'really like', 'all the REST of them!');    // Why does JS single out one parameter?  // Because it doesn't  // really like  // all the REST of them!
# Python  def pirate_joke(question, *args):    print question    for arg in args:      print arg    python_joke = "What's a Pyrate's favorite parameter?"    pirate_joke(python_joke, "*args!", "*arrgs!", "*arrrgs!")    # What's a Pyrate's favorite parameter?  # *args!  # *arrgs!  # *arrrgs!

6. Classes:类

众所周知,ES6类实际上是语法糖。Python具有内置的类,可以快速,轻松地进行面向对象的编程。

JavaScript原型链继承,是每个前端的必须课。

// JavaScript  class Mammal {    constructor() {      this.neocortex = true;    }  }    class Cat extends Mammal {    constructor(name, years) {      super();      this.name = name;      this.years = years;    }      eat(food) {      console.log('nom ' + food);    }  }
# Python  class Mammal(object):    neo_cortex = True    class Cat(Mammal):    def __init__(self, name, years):      self.name = name      self.years = years      def eat(food):      print 'nom %s' % (food)    fry_cat = Cat('Fry', 7)  fry_cat.eat('steak')

平心而论,Python的写法更优雅。。。

2. 前端如何优雅学会Python

许多前端对Python的热情始于好奇,终于停滞。

距离实干做开发有技术差距,也无人指点提带,也不知当下水平能干嘛?就在这样的疑惑循环中,编程技能止步不前,而爬虫是最好的进阶方向之一。

网络爬虫是Python比较常用的一个场景,国际上,google在早期大量地使用Python语言作为网络爬虫的基础,带动了整个Python语言的应用发展。

就我个人发展而已,我也十分推荐以爬虫为应用入门,原因有几项:

  • 爬虫是针对web页面的一种应用技术,前端可以无痛衔接很多知识。
  • 爬虫的第一步是获取页面源码,然后做信息抽取。其中针对dome节点的class/id选择,前端无需再度学习。
  • 爬虫中的虚拟登录及Selenium,可以提升前端对于自动化测试的理解。
  • 爬虫的最终形态是搜索引擎,当中的SEO是每个前端都需要关注的点儿。
  • 在了解搜索引擎爬虫的过程中,前端可以搞清楚服务端渲染SSR和单页应用CSR的不同作用。

爬虫分两种方式:面向页面和面向接口

  • 面向页面,前端自然轻车熟路。
  • 面向接口,需要了解到如何用抓包软件(Fiddler/Charles)。
  • 在这过程中,又能学会一项技能 – 抓包。以后不用再看着Network傻傻刷新了。

始于爬虫,却不止于爬虫:

爬虫—> 数据清洗 -> 数据库操作 -> 数据清洗 -> 数据挖掘 -> 数据分析 …

这一条链下去,你可以学到非常非常多的知识:

Scrapy爬虫框架,Redis分布式事务,数据处理Pandas,自然语言分析NLP,完整实现数据可视化等等….

3,潘石屹都在学Python

别犹豫了,跟着劝退师一起学吧。

小号- Python劝退师(会陆续更新)

❤️ 看完三件事

如果你觉得这篇内容对你挺有启发,我想邀请你帮我三个小忙:

  1. 点赞,让更多的人也能看到这篇内容(收藏不点赞,都是耍流氓 -_-)
  2. 关注公众号「前端劝退师」,不定期分享原创知识。
  3. 也看看其它文章

也可以来我的GitHub博客里拿所有文章的源文件:

前端劝退指南:https://github.com/roger-hiro/BlogFN

参考资料

[1]

How Python can help you learn ES6 : https://blog.logrocket.com/how-python-can-help-you-learn-es6/