JS Python and what is similar?

Python is a very extensive use of language, automated script, reptiles, even in the depth of field of study also have Python figure. As a front-end developer, ES6 also understand the many features borrowed from Python (such as the default parameters, destructuring assignment, Decorator, etc.), while some uses of this article will Python and JS analogy. Whether to upgrade their breadth of knowledge, or to better meet the AI ​​era, Python is a language worth learning.

type of data

In Python, the most commonly used type of data can be processed directly are the following:

  • Digital [integer (int), float (float), long integer (long), complex (Complex)]
  • String (str)
  • Boolean value (bool)
  • Null (None)

In addition, Python also provides a list of [List], Dictionary [dict], and other data types, which are described below.

Type conversion and type judgment

Very similar to JS, Python force can be achieved with the implicit conversion between different data types, the following examples:

Cast:

int('3')# 3
str(3.14)# '3.14'
float('3.14')# 3.14
# 区别于 JS 只有 Number 一种类型,Python 中数字中的不同类型也能相互强制转换
float(3)# 3.0
bool(3)# True
bool(0)# False

Implicit type conversions:

1+1.0# 2.0
1+False# 1
1.0+True# 2.0
# 区别于 JS 的 String + Number = String, py 中 str + int 会报错
1+'1'# TypeError: cannot concatenate 'str' and 'int' objects

Further write the code often need type judgment value, may be used provided Python type () function to get the type of a variable, or to use the isinstance (x, type) to determine whether the respective type x type.

type(1.3)==float# True
isinstance('a', str)# True
isinstance(1.3,int)# False
isinstance(True,bool)# True
isinstance([], list)# True
isinstance({}, dict)# True

Indexed collections

A collection is a data structure comprises a set of elements, i.e., the ordered set is the set of elements inside arranged in the order, the ordered set of Python about the following categories: list, tuple, str, unicode.

Type list

Python is similar in type JS List of Array,

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
L =[1,2,3]
print L[-1]# '3'

L.append(4)# 末尾添加元素
print L # [1, 2, 3, 4]

L.insert(0,'hi')# 指定索引位置添加元素
print L # ['hi', 1, 2, 3, 4]

L.pop()# 末尾移除元素 L.pop(2) ?????? 2 ???
print L # ['hi', 1, 2, 3]

tuple type

tuple type is another ordered list, the Chinese translation for "tuple." tuple and the list is very similar, however, tuple Once created, it can not be modified.

t =(1,2,3)
print t[0]# 1
t[0]=11# TypeError: 'tuple' object does not support item assignment

t =(1)
print t # 1  t 的结果是整数 1

t =(1,)# 为了避免出现如上有歧义的单元素 tuple,所以 Python 规定,单元素 tuple 要多加一个逗号","     
print t # (1,)

Unordered collection type

dict type

Python is similar in type dict} {(biggest difference is that it is not order) of the JS, which has the following characteristics:

  • Find a fast speed (dict whether there are 10 elements or 100,000 elements, the search speed are the same)
  • Memory for large (as opposed to list type)
  • The key can not be repeated dict
  • dict stored key-value pair is not ordered sequence
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
d ={
   'a':1,
   'b':2,
   'c':3
}

print d # {'a': 1, 'c': 3, 'b': 2}  可以看出打印出的序对没有按正常的顺序打出

# 遍历 dict
for key,value in d.items():
   print('%s: %s'%(key,value))
# a: 1
# c: 3
# b: 2

set type

Sometimes, we just want dict key, and do not care key corresponding to the value, but also to ensure that this element of the set will not be repeated, this time, set the type comes in handy. set type has the following characteristics:

  • Similar elements set and stored dict the key, it must be immutable objects
  • Set of elements is not stored in the order
s =set(['A','B','C','C'])
print s # set(['A', 'C', 'B'])

s.add('D')
print s # set(['A', 'C', 'B', 'D'])

s.remove('D')
print s # set(['A', 'C', 'B'])

Python is an iterative

After the presentation of the ordered set Python and unordered collection type, there must be set for looping through. But the standard for other languages ​​and different cycle, all iterations in Python by for ... in to complete. The following gives some common iteration demos:

Index iteration:

L =['apple','banana','orange']
for index, name in enumerate(L):  
# enumerate() 函数把 ['apple', 'banana', 'orange'] 
# 变成了类似 [(0, 'apple), (1, 'banana'), (2, 'orange')] 的形式
   print index,'-', name

# 0 - apple
# 1 - banana
# 2 - orange

Iteration dict of value:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
d ={'apple':6,'banana':8,'orange':5}
print d.values()# [6, 8, 5]
for v in d.values()
   print v
# 6
# 8
# 5

Dict iteration of key and value:

d ={'apple':6,'banana':8,'orange':5}
for key, value in d.items()
   print key,':', value
# apple : 6
# banana: 8
# orange: 5

Slicing operation

Python slicing operation similar to that provided by the native function slice JS provided (). With the slicing operation, greatly simplifying the operation of some of the original starting cycle.

L =['apple','banana','orange','pear']
L[0:2]# ['apple', 'banana'] 取前 2 个元素
L[:2]# ['apple', 'banana'] 如果第一个索引是 0,可以省略
L[:]# ['apple', 'banana', 'orange', 'pear'] 只用一个 : ,表示从头到尾
L[::2]# ['apple', 'orange'] 第三个参数表示每 N 个取一个,这里表示从头开始,每 2 个元素取出一个来

List Builder

If you want to generate [1x1, 2x2, 3x3, ..., 10x10] how to do? The first loop method:

L =[]
for x in range(1,11):
   L.append(x * x)

However, the cycle too complicated, and the list of the formula may be replaced with a circulation line list generated above statement:

# 把要生成的元素 x * x 放到前面,后面跟 for 循环,就可以把 list 创建出来
[x * x for x in range(1,11)]
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

The formula for the list following the loop can also add the if (JS similar in filter () function), for example:

[x * x for x in range(1,11)if x %2==0]
# [4, 16, 36, 64, 100]

for loops can be nested, therefore, in the list in the formula, it can also be used for multilayer loop generating a list.

[m + n for m in'ABC'for n in'123']
# ['A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']

Python functions

The default parameters

JS ES6 default parameters in precisely borrowed from Python, is used as follows:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
def greet(name='World'):
   print'Hello, '+ name +'.'

greet()# Hello, World.
greet('Python')# Hello, Python.

variable parameter

JS function similar to automatically recognize the number of parameters passed, Python also provides a definition of the variable parameters, i.e., a band in front of the name of the variable parameter *number.

def fn(*args):
   print args

fn()  # ()
fn('a')# ('a',)
fn('a','b')# ('a', 'b')

Python interpreter will pass a set of parameters passed to assembly into a tuple of variable parameters, therefore, within the function, the variable directly as a tuple args like.

Common higher-order functions

Python effect commonly used functions (map, reduce, filter), and the JS same, but slightly different usage.

  • map function: a function f and a reception list, and the function f are sequentially by acting on each element of the list to obtain a new list and returns.
def f(x):
   return x * x
print map(f,[1,2,3,4,5,6,7,8,9])# [1, 4, 9, 16, 25, 36, 49, 64, 81]
  • reduce function: a function f and a reception list (acceptable third value as an initial value), reduce () for each element of the list of frequently called function f, and returns the final result value.
def f(x, y):
   return x * y

reduce(f,[1,3,5])# 15
  • The filter function: receiving a function f and a list, the role of this function f is determined for each element, returns True or False, filter () filter based on the determination result does not conform to the conditions of the elements, elements returned by qualified the new list.
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
def is_odd(x):
   return x %2==1

filter(is_odd,[1,4,6,7,9,12,17])# [1, 7, 9, 17]

Anonymous function

JS anonymous functions and different places, Python anonymous function can have only one expression, and can not write return. Take the map () function as an example:

map(lambda x: x * x,[1,2,3,4,5,6,7,8,9])# [1, 4, 9, 16, 25, 36, 49, 64, 81]

Keywords lambda represents the anonymous function, before the colon x represents a function parameter, you can see anonymous function lambda x: x* xis actually:

def f(x):
   return x * x

Closure

Prior written some articles about JS closures, such as JavaScript in simple terms the closure (Closure), and reading notes - JavaScript (on) you do not know, in the definition and JS Python closure is consistent, namely: within function reference variable outer layer function, and then return the inner function. Let's look at the classic problem for loop closure of the Py:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
# 希望一次返回3个函数,分别计算1x1,2x2,3x3:
def count():
   fs =[]
   for i in range(1,4):
       def f():
           return i * i
       fs.append(f)
   return fs

f1, f2, f3 = count()# 这种写法相当于 ES6 中的解构赋值
print f1(), f2(), f3()# 9 9 9

Old problems, f1 (), f2 (), f3 () should not be the result of 1, 4, 9 it, why the actual result is 9 it?

The reason is that when the count () function returns the three functions, three values of the variable i in a reference function has become 3. Since f1, f2, f3 is not called, so, at this time they do not calculate i*i, when f1 is called, i have become 3 a.

To properly use a closure, it is necessary to ensure that references to local variables can not be changed after the function returns. Code changes as follows:

Method one: create can be understood as a closed scope, the value of i after a pass j, and i just did not have any relationship. Closures are deposited each cycle formed into memory.

def count():
   fs =[]
   for i in range(1,4):
       def f(j):
           def g():# 方法一
               return j * j
           return g
       r = f(i)
       fs.append(r)
   return fs

f1, f2, f3 = count()
print f1(), f2(), f3()# 1 4 9

Method Two: Comparative ingenious idea, the default parameters used in the function definition j to the value of i may be obtained, though not used closures, and but a method would be similar.

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
def count():
   fs =[]
   for i in range(1,4):
       def f(j = i):# 方法二
           return j * j
       fs.append(f)
   return fs

f1, f2, f3 = count()
print f1(), f2(), f3()# 1 4 9

decorator decorator

Syntax decorator ES6 exactly what draws the Python decorator. The decorator is essentially a higher order function, a function which receives as an argument, and returns a new function.

That the role of decorator Where is it? First on the gateway code for some everyday items used ts wrote:

@Post('/rider/detail')  // URL 路由
@log()                   // 打印日志
 @ResponseBody
 publicasync getRiderBasicInfo(
   @RequestBody('riderId') riderId: number,
   @RequestBody('cityId') cityId: number,
 ){
   const result =awaitthis.riderManager.findDetail(cityId, riderId)
   return result
 }

It can be seen decorator greatly simplifies code without each function (such as logging, route, performance testing) write repetitive code.

Back to Python, @ Python provides syntax to use decorator, @ is equivalent to f = decorate (f). Here's a look @log (achieve) in Python:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
# 我们想把调用的函数名字给打印出来
@log()
def factorial(n):
   return reduce(lambda x,y: x*y, range(1, n+1))
print factorial(10)

# 来看看 @log() 的定义
def log():
   def log_decorator(f):
       def fn(x):
           print'调用了函数'+ f.__name__ +'()'
           return f(x)
       return fn
   return log_decorator

# 结果
# 调用了函数 factorial()
# 3628800

class

Object-Oriented Programming

Object-oriented programming is a programming paradigm, the basic idea is: abstract class definition type, and then create an instance of the class definition. On the basis of the grasp of other languages, it is quite easy to understand the point of this piece of knowledge, such as can be seen from the following two written yet there are so many similarities between the language features of different languages.

ES6: (attached: the subject matter herein is python, so just a little early impressions create a definition and examples of the lower class js, to illustrate the similarity of writing)

classPerson{
   constructor(name, age){
       this.name = name
       this.age = age
   }
}

const child1 =newPerson('Xiao Ming',10)

Python: (core elements of writing in the comment)

# 定义一个 Person 类:根据 Person 类就可以造成很多 child 实例
classPerson(object):
   address ='Earth'# 类属性 (实例公有)
   def __init__(self, name, age):# 创建实例时,__init__()方法被自动调用
       self.name = name
       self.age = age
   def get_age(self):
   # 定义实例方法,它的第一个参数永远是 self,指向调用该方法的实例本身,其他参数和普通函数是一样的
       returnself.age

child1 =Person('Xiao Ming',10)
child2 =Person('Xiao Hong',9)

print child1.name # 'Xiao Ming'
print child2.get_age()# 9
print child1.address # 'Earth'
print child2.address # 'Earth'

inherit

child belongs to the class Student, Student category is People category, which leads to inherit: can add your own methods to obtain a property that is property of the parent class method after.

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
classPerson(object):
   def __init__(self, name, age):
       self.name = name
       self.age = age

classStudent(Person):
   def __init__(self, name, age, grade):
       super(Student,self).__init__(name, age)# 这里也能写出 Person.__init__(self, name, age)
       self.grade = grade

s =Student('Xiao Ming',10,90)
print s.name # 'Xiao Ming'
print s.grade # 90

Subclass can be seen on the basis of the parent class on the addition of grade properties. We can look at the type of s.

isinstance(s,Person)
isinstance(s,Student)

As can be seen, Python in succession on a chain, can be seen as an instance of its own type, it can be seen as the type of the parent class.

Guess you like

Origin blog.51cto.com/14246112/2455819