What are the similarities between Python and JS?

Python is a widely used language. It can automate scripts, crawlers, and even in the field of deep learning. As a front-end developer, I also know that many features in ES6 are borrowed from python (such as default parameters, deconstruction and assignment, Decorator, etc.), at the same time, this article will compare some uses of python with JS. Python is a language worth learning whether it is to improve its knowledge scope or better meet the AI era.

data type

In Python, the most commonly used data types that can be processed directly are as follows:

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

In addition, Python provides a variety of data types, such as list, dict, which will be described in the following.

Type conversion and type judgment

Very similar to JS, python can also implement forced and implicit conversion between different data types, for example:

Cast:

int('3')# 3
str(3.14)# '3.14'
float('3.14')# 3.14
# Different from JS, which only has Number, different types of numbers in Python can also cast each other
float(3)# 3.0
bool(3)# True
bool(0)# False

Implicit type conversion:

1+1.0# 2.0
1+False# 1
1.0+True# 2.0
# String + number = string different from JS, str + int in py will report an error
1+'1'# TypeError: cannot concatenate 'str' and 'int' objects

In addition, when writing code, you often need to determine the type of value. You can use the type() function provided by python to get the type of variable, or use isinstance(x, type) to determine whether x belongs to the corresponding 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

Ordered set type

A set is a data structure that contains a group of elements. An ordered set is a set in which the elements are arranged in order. There are several types of ordered sets in Python: list, tuple, str, unicode.

list type

List type in Python is similar to Array in JS,

L =[1,2,3]
print L[-1]# '3'

L.append(4)# Add element at end
print L # [1, 2, 3, 4]

L.insert(0,'hi')# Specify index location add element
print L # ['hi', 1, 2, 3, 4]

L.pop()# Remove the element l.pop (2) at the end???
print L # ['hi', 1, 2, 3]

tuple type

Tuple type is another kind of ordered list, which is translated as "tuple" in Chinese. Tuple is very similar to list, but once the tuple is created, it cannot 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 # The result of 1 t is the integer 1
 
t =(1,)# In order to avoid the above ambiguous single element tuple, Python stipulates that the single element tuple should be added with a comma "."     
print t # (1,)

Unordered set type

dict type

The dict type in Python is similar to {} in JS (the biggest difference is that it has no order). It has the following characteristics:

  • Fast search speed (whether dict has 10 elements or 100000 elements, the search speed is the same)
  • Large memory consumption (opposite to list type)
  • key in dict cannot be repeated
  • The key value sequence pair stored in dict has no sequence
d ={
   'a':1,
   'b':2,
   'c':3
}

print d # {'a': 1, 'c': 3, 'b': 2} it can be seen that the printed sequence pairs are not printed in the normal sequence

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

set type

Sometimes, we just want the key of dict, and we don't care about the value corresponding to the key, and we need to make sure that the elements of this set won't be repeated. At this time, the set type is useful. The set type has the following characteristics:

  • The element stored in set is similar to the key of dict, and must be immutable
  • The elements stored in set also have no 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'])

Iterations in Python

After introducing the ordered and unordered set types in Python, there must be a for loop that traverses the set. But unlike standard for loops in other languages, all iterations in Python are done through for... In. Here are some common iterative demos:

Index iteration:

L =['apple','banana','orange']
for index, name in enumerate(L):  
# The enumerate() function takes ['apple ',' Banana ',' Orange '] 
# It becomes something like [(0, 'Apple), (1,' Banana '), (2,' Orange ')]
   print index,'-', name
 
# 0 - apple
# 1 - banana
# 2 - orange

value of iterative dict:

d ={'apple':6,'banana':8,'orange':5}
print d.values()# [6, 8, 5]
for v in d.values()
   print v
# 6
# 8
# 5

key and value of iterative dict:

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

PS: no one answers the questions? Need Python learning materials? You can click the link below to get it by yourself
note.youdao.com/noteshare?id=2dce86d0c2588ae7c0a88bee34324d76

Slice operator

The slice operator provided by Python is similar to the native function slice() provided by JS. With the slicing operator, it greatly simplifies the operation of some original loops.

L =['apple','banana','orange','pear']
L[0:2]# ['apple ','banana'] take the first two elements
L[:2]# ['apple ','banana'] if the first index is 0, it can be omitted
L[:]# ['apple ',' Banana ',' Orange ',' pear '] only one:, means from beginning to end
L[::2]# ['apple ','Orange'] the third parameter means to take one out of every N, which means to start from scratch and take one out of every 2 elements

List builder

How to generate [1x1, 2x2, 3X3,..., 10x10]? The first method is circulation:

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

However, the cycle is too cumbersome, and the list generation can use one line of statements instead of the cycle to generate the above list:

# The list can be created by putting the element x * x to be generated first, followed by the for loop
[x * x for x in range(1,11)]
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

if judgment (similar to filter() function in JS) can be added after the for loop of list generation type. The example is as follows:

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

For loops can be nested, so in list generation, you can also generate lists with multiple for loops.

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

Python functions

Default parameters

The default parameters of ES6 in JS are just borrowed from Python. The usage is as follows:

def greet(name='World'):
   print'Hello, '+ name +'.'
  
greet()# Hello, World.
greet('Python')# Hello, Python.

Variable parameters

Similar to the automatic identification of the number of incoming parameters in JS functions, Python also provides the definition of variable parameters, that is, the variable parameter name is preceded by a * sign.

def fn(*args):
   print args
 
fn()  # ()
fn('a')# ('a',)
fn('a','b')# ('a', 'b')

The Python interpreter will assemble a group of passed in parameters into a tuple and pass it to the variable parameter. Therefore, in the function, it is better to directly treat the variable args as a tuple.

Common higher order functions

The functions commonly used in Python (map, reduce, filter) have the same function as in JS, but with slightly different usage.

  • map function: receive a function f and a list, and by applying the function f to each element of the list in turn, get a new list and return it.
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: receive a function f and a list (the third value can be accepted as the initial value). reduce() calls function f repeatedly for each element of the list and returns the final result value.
def f(x, y):
   return x * y
 
reduce(f,[1,3,5])# 15
  • filter function: receive a function f and a list. The function f is to judge each element and return True or False. filter() automatically filters out unqualified elements according to the judgment result and returns a new list composed of qualified elements.
def is_odd(x):
   return x %2==1
  
filter(is_odd,[1,4,6,7,9,12,17])# [1, 7, 9, 17]

Anonymous function

Unlike JS anonymous functions, Python anonymous functions can only have one expression and cannot write return. Take the map() function for example:

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

The keyword lambda represents anonymous function, and the X before the colon represents function parameter. It can be seen that the anonymous function lambda x: x* x is actually:

def f(x):
   return x * x

closure

I've written some articles about JS closures before, such as the close in JavaScript, and reading notes - Javascript you don't know (I). The definition of closures in Python is consistent with that in JS, that is, the inner function references the variables of the outer function, and then returns the inner function. Let's look at the classic for loop problem of closures in Py:

# You want to return three functions at a time, and calculate 1x1,2x2,3x3 respectively:
def count():
   fs =[]
   for i in range(1,4):
       def f():
           return i * i
       fs.append(f)
   return fs
 
f1, f2, f3 = count()# This method is equivalent to the deconstruction assignment in ES6
print f1(), f2(), f3()# 9 9 9

The old question, f1(), f2(), f3() result should not be 1, 4, 9, why are the actual results all 9?

The reason is that when the count() function returns three functions, the value of variable i referenced by these three functions has become three. Since f1, f2 and f3 are not called, they do not calculate i*i at this time. When f1 is called, i has become 3.

To use closures correctly, make sure that the referenced local variable does not change after the function returns. The code is modified as follows:

Method 1: it can be understood that a closed scope is created. After i's value is passed to j, it has nothing to do with i. The closure formed by each loop is stored in memory.

def count():
   fs =[]
   for i in range(1,4):
       def f(j):
           def g():# Method 1
               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 2: the idea is more ingenious. The default parameter j is used to get the value of i when defining the function. Although the closure is not used, it is similar to method 1.

def count():
   fs =[]
   for i in range(1,4):
       def f(j = i):# Method two
           return j * j
       fs.append(f)
   return fs
  
f1, f2, f3 = count()
print f1(), f2(), f3()# 1 4 9

decorator

The decorator in ES6's syntax is just a reference to Python's decorator. Decorator is essentially a higher-order function that takes a function as an argument and returns a new function.

What is the function of the ornament? First, the gateway code written in ts in the previous daily project:

@Post('/rider/detail')  // URL routing
@log()                   // Print log
 @ResponseBody
 publicasync getRiderBasicInfo(
   @RequestBody('riderId') riderId: number,
   @RequestBody('cityId') cityId: number,
 ){
   const result =awaitthis.riderManager.findDetail(cityId, riderId)
   return result
 }

You can see that using decorators can greatly simplify the code and avoid writing repetitive code for each function (such as log, routing, performance detection).

Back in Python, python provides the @ syntax to use decorator, @ is equivalent to f = decorate(f). Let's take a look at the implementation of @ log() in Python:

# We want to print out the name of the called function
@log()
def factorial(n):
   return reduce(lambda x,y: x*y, range(1, n+1))
print factorial(10)
 
# Let's see the definition of @ log()
def log():
   def log_decorator(f):
       def fn(x):
           print'Function called'+ f.__name__ +'()'
           return f(x)
       return fn
   return log_decorator

# Result
# Function factorial() called
# 3628800

class

object-oriented programming

Object oriented programming is a programming paradigm. The basic idea is to define abstract types with classes, and then create instances according to the definitions of classes. On the basis of mastering other languages, it is easier to understand this knowledge. For example, from the following two writing methods, we can see that there are so many similarities between the language characteristics of different languages.

es6: (attachment: the topic of this article is python, so it just shows the definition of classes and the creation of instances in js, in order to illustrate the similarity of writing methods.)

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

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

Python: (the key points are written in the notes)

# Define a Person class: many child instances can be created according to the Person class
classPerson(object):
   address ='Earth'# Class properties (instance public)
   def __init__(self, name, age):# When an instance is created, the \\\\\\\\
       self.name = name
       self.age = age
   def get_age(self):
   # Define the instance method. Its first parameter is always self, which points to the instance calling the method itself. Other parameters are the same as ordinary functions
       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 Student class and Student belongs to the People class, which leads to inheritance: that is, after obtaining the method properties of the parent class, you can add your own method properties.

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)# You can also write person. Init (self, name, age)
       self.grade = grade
  
s =Student('Xiao Ming',10,90)
print s.name # 'Xiao Ming'
print s.grade # 90

You can see that the child class adds grade attribute on the basis of the parent class. Let's look at the type of S.

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

As you can see, in Python, an instance can be regarded as its own type or the type of its parent class in an inheritance chain.

Tags: Python Lambda Programming Javascript

Posted on Tue, 03 Dec 2019 13:43:55 -0500 by rgilchrist