3

Python for JavaScript Developer

 3 years ago
source link: https://www.luxianpo.com/tech/python-for-javascript.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Python for JavaScript Developer

我的日常主要是写 JavaScript,这篇文章的原始内容来自于我读 《Python 编程:从入门到实践》的读书笔记。分享从 JavaScript 开发者的角度出发来学习 Python 这门语言。在 JS 的基础上学习一门的新的语言,会降低非常多的入门成本。

语法上的差异

想要实际感受一下代码的运行效果可以在 https://repl.it/languages/python3 这个上面尝试

  1. 不在需要写 let、var 之类的声明,同时没有自动的类型转换
age = 23
message = "Happy "+str(age)+"rd Birthday!"
print(message)
  1. 注释使用 #
# print hello world
print("hello world")
  1. 数组操作 push 使用 append,插入使用 insert,删除使用 del,取出元素 pop,根据值删除元素 remove
list = ['a', 'b']
list.append('c')
list.insert(4, 'd')
del list[0]
lastListItem = list.pop() # 取出最后一个
firstListItem = list.pop(0) # 取出任意位置的元素
list.remove('b')  # 根据值来删除
  1. 循环使用 for ... in
list = ['a', 'b', 'c', 'd']

for item in list:
    print(item)
  1. 数值列表 range
  2. python 里面数组中间的获取,使用切片
  3. 元祖是一个只能整个变的变量
dimensions = (200, 50)
print("Original dimensions:")
for dimension in dimensions:
    print(dimension)

dimensions = (400, 100)
print("Modified dimensions:")
for dimension in dimensions:
    print(dimension)
  1. & -> and,|| -> or
a = 1
b = 2

print(a >= 1 and b >= 3) # False
print(a >= 1 or b >= 3) # True
  1. 布尔值首字母大写,isOk = True, isOk= False
  2. else if 简化为 elif
  3. 访问对象内的值统一使用 dic['a'] 的形式,同时对象的 key 也要带上单引号,dicTest = {'a': 'aValue'}
  4. 删除对象使用 del dicTest['a']
  5. 遍历使用: for key, value in dicTest.items()
  6. Object.keys(dicTest) -> dicTest.keys(),Object.values(dicTest) -> dicTest.values()
  7. 函数通过 def 声明

    函数整体比较复杂,更加详细的部分大家可以看:Python 编程:从入门到实践 · 函数

def greet_user():
    # 特殊的注释
    """显示简单的问候语"""
    print("Hello!")
greet_user()
class Dog():
    """一次模拟小狗的简单尝试"""
    def __init__(self, name, age):  # __init__ 类比 JS 中的 constructor
        """初始化属性name和age"""
        self.name = name
        self.age = age
    def sit(self):
        """模拟小狗被命令时蹲下"""
        print(self.name.title()+" is now sitting.")
    def roll_over(self):
        """模拟小狗被命令时打滚"""
        print(self.name.title()+" rolled over!")

myDog = Dog('dogName', 16)  # 不需要 new

# 调用和 JS 基本相同
print(myDog.name)
myDog.sit()


# 类的继承
class SuperDog(Dog):
    def __init__(self, name, age):
        super().__init__(name, age)
        self.isSuper = True

mySuperDog = SuperDog('super', 1)
print(mySuperDog.isSuper)
mySuperDog.sit()

和 JS 的 ESModule 语法类似

# dog.py 内容和上面的 Dog 类相同

# main.py

# 单个导入
from dog import Dog, SuperDog


# 整个导入
import dog
myDog = dog.Dog('name', 10)

Pyhone 使用 pip:https://pip.pypa.io/en/stable/

以上是在阅读 《Python 编程:从入门到实践》 的一些关键点的摘录,还是很推荐可以阅读一下这本书的原文。Pyhone 其实没有像中的那么难,有很多还是和 JS 很像的,在 JS 的基础上可以很快上手。

最后分享非常喜欢书中献言部分,很暖:

谨以此书献给我的父亲,以及儿子 Ever。感谢父亲抽出时间来回答我提出的每个编程问题,而儿子 Ever 也开始向我提问了。

#tech

2020-05-30 杭州


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK