面向 JavaScript 开发人员的 Python
所以最近我开始在纽约一家名为Underdog.io的小型创业公司工作,在那里我发现他们的后端主要用 Python 编写,而我之前很少接触这种语言。
虽然我被录用主要是因为我在 JavaScript 和 React 方面的经验,但由于团队规模较小,为了发布一个功能,我经常需要深入研究代码库的各个部分。因此,我必须非常快速地熟悉 Python。
不幸的是,我很难找到适合那些没有编程经验的人学习 Python 的好资源。我已经会编程了,也熟悉其他语言,我只需要学习 Python 这门特定编程语言的语法和范式。
这就是这篇博文的意义所在。它为想要快速掌握 Python 的 JavaScript 开发人员提供快速指南,但无需了解声明变量的含义或函数的含义。
这篇文章假设您使用的是Python 3.0.1,因此某些示例可能不适用于旧版本的 Python。
句法
声明变量
在 Python 中声明变量非常简单。与 JavaScript 类似,声明变量时无需设置其类型,也无需声明变量的作用域(let
vs var
):
x = 5
您可以通过为变量分配不同类型的值来更改变量的类型:
x = 5 # x has a type of Integer
x = 'Hewwo' # x is now a String!
与 JavaScript 不同,Python 中的变量始终是块作用域的。
区块
Python 的语法比 JavaScript 更严格一些。在 Python 中,哪怕少了一个空格的缩进都会导致你的程序无法运行!这是因为 Python 使用缩进来创建块,而不是使用括号。例如,在 JavaScript 和 Python 中,块的定义方式如下:
在 JavaScript 中创建块
function exampleFunction () {
// This is a block
var a = 5;
}
{
// This is also a block
}
在 Python 中创建块
# This is a block with its own scope
def example_function():
# This is also a block with its own scope
x = 5
print(x)
如果包含的行print(x)
有一个或多个多余的空格,Python 解释器就会抛出一个IndentationError
,因为这些多余的空格会创建一个无效的块。
def example_function():
x = 5
# IndentationError!
print(x)
如果同一行中少了一个或多个空格,如下所示:
def example_function():
x = 5
print(x)
Python 解释器会抛出这个错误:
NameError: name 'x' is not defined
因为print(x)
它位于超出声明范围的块中x
。
控制流
if...else
Python 中的、while
、 和for
块与 JavaScript 非常相似:
如果...否则
if x > 2:
print('hai!')
elif x > 3:
print('bye!')
else:
print('hey now')
if not x:
print('x is falsy!')
while 循环
while x > 0:
print('hey now')
for 循环
For 循环类似于 JavaScriptforeach
循环:
ex_list = [1, 2, 3]
for x in ex_list:
print(x)
类型
Python 的类型系统与 JavaScript 非常相似;它确实存在,但不像 Java 或 C# 等其他语言那样严格。
实际上,变量有类型,但您不必像在 Java 等静态类型语言中那样声明变量的类型。
以下是 Python 内置数据类型的简要概述:
数字
与 JavaScript 不同,Python 具有多种数字类型:
- 整数:
1
,,2
3
- 浮点数:
4.20
,4e420
- 复数:
4 + 20j
- 布尔值:
True
,False
Python 中的数字运算与 JavaScript 中的相同。此外,还有一个指数运算符 (**):
# a = 4
a = 2 ** 2
列表
Python 中的列表类似于 JavaScript 中的数组。列表可以包含多种类型:
[4, "2", [0, "zero"]]
还有一种从列表中切片元素的特殊语法:
a_list = [1, 2, 3, 4, 5]
# 1, 2, 3
a_list[0:2]
# 4, 5
a_list[3:]
# 3, 4
a_list[2, -2]
还有一些用于操作列表的方便的内置方法:
# 3
len([1, 2, 3])
# 3, 2, 1
[1, 2, 3].reverse()
# 1, 2, 3
[1, 2].append(3)
您甚至可以使用+
运算符连接两个列表:
# 1, 2, 3, 4
[1, 2] + [3, 4]
字符串
Python 中的字符串与 JavaScript 中的字符串非常相似。它们是不可变的,并且单个字符可以像数组中的元素一样访问:
name = 'Mario'
# M
print(name[0])
# Nope, name is still 'Mario'
name[0] = 'M'
字典
字典是关联数组,类似于 JavaScript 中的对象。实际上,字典可以用类似 JSON 的语法声明:
# Dictionaries in python
person = {
'name': 'Mario',
'age': 24
}
# Mario
print(person['name'])
当尝试获取不存在的键的值时,字典有一个方便的方法可以返回默认值:
# Because `gender` is not defined, non-binary will be returned
person.get('gender', 'non-binary')
没有任何
None
相当于null
JavaScript 中的 。它表示值不存在,因此被视为“假”。
x = None
if not x:
print('x is falsy!')
功能
与 JavaScript 类似,Python 中的函数也是对象。这意味着你可以将函数作为参数传递,甚至可以为函数赋值:
def func(a, fn):
print(a)
fn()
func.x = 'meep'
# 'meep'
print(func.x)
def another_func():
print('hey')
# 5
# 'hey'
func(5, another_func)
模块
Python 中的模块与 ES6 中的模块差别并不大。
定义模块
Python 中的模块只是一个包含一些 Python 代码的文件。
# my_module.py
hey = 'heyyy'
def say_hey():
print(hey)
与 JavaScript 不同,您不必声明要导出什么;默认情况下会导出所有内容。
导入模块
您可以在 Python 中导入整个模块:
# importing my_module.py from another_module.py; both files are in the same
# directory
import my_module
# Do things
my_module.say_hey()
print(my_module.hey)
或者从模块导入单个项目:
# another_module.py
from my_module import hey, say_hey
# Do things
say_hey()
print(hey)
您还可以使用pip(Python 的包管理器)安装其他人编写的模块。
pip install simplejson
面向对象编程
Python 支持具有类和经典继承的面向对象编程,而 JavaScript 则具有具有原型继承的原型。
课程
# Defining a class
class Animal:
# Variable that is shared by all instances of the Animal class
default_age = 1
# Constructor
def __init__(self, name):
# Defining a publicly available variable
self.name = name
# You can define private variables and methods by prepending the variable
# name with 2 underscores (__):
self.__age = default_age
# Public method
def get_age(self):
return self.__age
# Private method
def __meow():
print('meowwww')
# Defining a static method with the `staticmethod` decorator
@staticmethod
def moo():
print('moooo')
# Creating an Animal object
animal = Animal()
# Accessing public variables and methods
print(animal.name)
print(animal.default_age)
print(animal.get_age())
# Accessing a static method
Animal.moo()
# ERR!!!! .__age is private, so this won't work:
print(animal.__age)
遗产
类可以从其他类继承:
# Inheriting from the Animal class
class Human(Animal):
def __init__(self, name, address):
# Must call the __init__ method of the base class
super().__init__(name)
self.__address = address
def get_address(self):
return self.address
# Using the Human class
human = Human('Mario', '123 Jane Street, Brooklyn, NY 11211')
# Human objects have access to methods defined in the Animal base class
human.get_age()
human.get_address()
资源
Python 的内容远不止本指南所介绍的内容。我强烈建议您查看Python 文档,获取更多教程以及有关其他语言功能的详细信息。
记住,学习一门语言的最好方法就是多写多练。所以,开始写代码吧!
PS:如果您需要一个项目想法,也许尝试使用Flask创建一个简单的 API ?
文章来源:https://dev.to/underdogio/python-for-javascript-developers