Python and Javascript Comparison

Source: Internet
Author: User
Recently, because of the need for work to start developing some python, because of the previous use of JavaScript, so will unconsciously use some of the concept of JavaScript, grammar, and often fall into the pit. I think it's necessary to summarize the differences between JavaScript and Python.

Basic concepts

Both Python and JavaScript are scripting languages, so they have many common features that require an interpreter to run, both dynamic types, support automatic memory management, and the ability to invoke eval () to execute scripts that are common to scripting languages.

However, they are also very different, JavaScript this design is a client-side scripting language, mainly used in the browser, its syntax mainly borrowed from C, and Python because of its "elegant", "clear", "simple" design and popular, is used in education, scientific computing, In different scenarios, such as web development.

Programming paradigm

Both Python and JavaScript support a number of different programming paradigms, which differ greatly in object-oriented programming. JavaScript Object-oriented is prototype-based (prototype), the object's inheritance is created by the prototype (also object), the object created by the prototype object inherits the method on the prototype chain. Python is a well-behaved class-based inheritance, and naturally supports polymorphism (Polymophine).

OO in Pyhton

Class Employee:   ' Common base class for all employees '   empcount = 0 # #类成员     def __init__ (self, Name, salary): = name      self.salary = Salary      Employee.empcount + 1        def displaycount (self):     print "total Employee%d "% employee.empcount     def displayemployee (self):      print" Name: ",,  ", Salary: ", Self.s alary## Create Instance EA = Employee ("a", +) EB = Employee ("B", "C") OO in Javascriptvar Empcount = 0;//constructor function Employee (name, S Alary) { = name;    This.salary = salary;       This.empcount + = 1;}  Employee.prototype.displayCount = function () {    console.log ("Total Employee" + Empcount);}  Employee.prototype.displayEmployee = function () {    console.log ("Name" + + ", Salary" + this.salary);} Create an instance var ea = new Employee ("a", + +), var EB = new Employee ("B", 2000);

Because it is object-based inheritance, in JavaScript, we have no way to use class member Empcount, we have to declare a global variable, of course, in the actual development we will use a more appropriate scope. Note that JavaScript creates objects that need to use the new keyword, which python does not need.

In addition to native prototype-based inheritance, there are many JavaScript oo tools that use closures or prototypes to emulate class inheritance, because it is not a property of the language itself and we don't discuss it.

Threading model

In the JavaScript world there is no multi-threading concept, and concurrency is done using event-driven methods, and all JavaScript programs run in one thread. The introduction of Web workers in HTML5 can concurrently handle tasks, but does not change the limitations of JavaScript single-threaded threads.

Python supports multithreading through the thread package.

Non-changing types (immutable type)

In Python, some data types are immutable, meaning that this type of data cannot be modified, and all modifications return new objects. All of the data types in JavaScript can be changed. Python introduces immutable types I think it's to support thread safety, and because JavaScript is a single-threaded model, there's no need to introduce immutable types.

Of course in JavaScript you can define an object's properties as read-only.

var obj = {};object.defineproperty (obj, "prop", {    value: "Test",    writable:false});

In ECMAScript5 support, you can also call the freeze method of the object to make it non-modifiable.

Object.freeze (obj)

Data type

JavaScript has a simple data type with object, String, Boolean, number, NULL, and undefined, with a total of six

Everything in Python is an object, like module, function, class, and so on.

Python has five built-in simple data types bool, int, long, float, and complex, plus container types, code types, internal types, and so on.


JavaScript has true and false. Python has true and false. They are no different than case.


JavaScript uses UTF16 encoding.

Python uses ASCII code. You need to call encode, decode to encode the conversion. Use the u as a prefix to specify that the string uses Unicode encoding.


All numeric types in JavaScript are implemented as 64-bit floating-point numbers. Nan (not a number) is supported, plus or minus infinity (+/-infiity).

Python has many numeric types, and the complex types are very handy, so it is very popular in research and education in Python. That should be one of the reasons. Nan is not defined in Python, except that the 0 operation throws an exception.


JavaScript has built-in array type (array is also object)

The list of Python and the array of JavaScript are closer, whereas tuples (tuple) can be understood as immutable lists.

In addition to finding the length in Python using the built-in method Len, basically JavaScript and Python provide a similar way to manipulate the list. Python has a very flexible and convenient operation for list subscripts, which is not in JavaScript. such as L[5:-1],l[:6] and so on.

Dictionaries, hash tables, objects

JavaScript uses {} to create objects that are indistinguishable from dictionaries and can use [] or. To access the members of an object. You can add, modify, and delete members dynamically. You can think of an object as a dictionary or hash table of JavaScript. The key of the object must be a string.

Python has a built-in hash table (dicts), and unlike JavaScript, dicts can have various types of key values.

Null value

JavaScript defines two types of null values. Undefined indicates that the variable is not initialized, and NULL indicates that the variable has been initialized but the value is empty.

There is no uninitialized value in Python, and if a variable value is null, Python uses none to represent it.

Declaration and initialization of variables in JavaScript

V1;v2 = Null;var V3;var v4 = Null;var v5 = ' something ';

In the code above, V1 is a global variable, uninitialized, a value of UNDEFINED;V2 is a global variable, initialized to a null value, V3 is a local uninitialized variable, v4 is a variable that is locally initialized to null, and V5 is a variable that is locally initialized to one character.

Declaration and initialization of variables in Python

V1 = None

V2 = ' someting '

Variable declaration and initialization in Python is a lot simpler. When a nonexistent variable is accessed in Python, an Nameerror exception is thrown. Attributeerror or Keyerror are thrown when the value of the object or dictionary is not present. So judging whether a value exists in JavaScript and Python requires a different way.

Check the existence of a variable in javascript:

if (!v) {    //do something if V does not exist or was null or is false}  if (v = = = undefined) {    //do something If v does not initialized}

Note that it is ambiguous to use!v to check if V is initialized because there are a number of cases where!v will return true

Check the existence of a variable in Python:

Try:    vexcept nameerror    # # do something if V does not exist

In Python it is also possible to determine if the variable exists by checking that the variable is not present in the local locals () or global globals ().

Type check

JavaScript can use typeof to get the type of a variable:

Examples of typeof in Javascript:

typeof 3//"number" typeof "ABC"//"string" typeof {}//"Object" typeof True//"boolean" typeof undefined//"undefined" ty peof function () {}//"function" typeof []//"object" typeof Null//"Object"

To be very careful with typeof, you can see from the above example that typeof null is actually an object. Because of the weakly-typed nature of the javscript, it is also necessary to use concepts such as instanceof,constructor for a more realistic type. Please refer to this article for details

Python provides a built-in method type to obtain the types of data.

>>> type ([]) is listtrue>>> type ({}) is dicttrue>>> type (") is strtrue>>> type (0) is Inttrue

The type of the class can also be judged by isinstance ().

Class A:    passclass B (a):    passisinstance (A (), a)  # returns Truetype (A ()) = = A      # returns Trueisinstance (b (), a)    # returns Truetype (B ()) = = A        # returns False

But notice that Python's class style has changed one time, not every version of Python runs the same behavior as the above code, in the old style, all instances of the type are ' instance ', so checking with the type method is not a good method either. This is similar to JavaScript.

Automatic type conversion

When working with different types of operations, JavaScript is always as automatic as possible for type conversions, which is convenient and, of course, error prone. Especially when it comes to numeric and string manipulation, it's a mistake to accidentally. I used to calculate various numeric properties in SVG, such as x, y coordinates, and when you accidentally add a string to a numeric value, JavaScript automatically converts a value, often nan, so that SVG is completely out of the picture, because automatic conversion is legal, Finding the wrong place is also very difficult.

Python is very cautious at this point and generally does not automatically convert between different types.



Python uses indentation to determine the end of a logical line is very creative, which is perhaps the most unique properties of Python, of course, some people are also very much criticized, especially the need to modify the refactoring code, modify the indentation will often cause a lot of trouble.

JavaScript Although the name of Java, its style is a bit like Java, but it and Java like Leifeng Pagoda and Lei Feng, really do not have a half-dime relationship. The syntax is similar to C at the time of the comparison. It is important to mention that Coffeescript, as a language built on JavaScript, uses a Python-like syntax and uses indentation to determine logical lines.

Python style

def func (list):    for I in range (0,len (list)):        print list[i]javascript style function Funcs (list) {    for (Var i=0, Len = List.length (); i < Len; i++) {        console.log (list[i]);}    }

As you can see from the above two code examples, Python is really concise.

Scope of action and package management

The scope of JavaScript is defined by the method function, which means that the same scope is inside the same method. This serious difference differs from the scope defined by the C language using {}. Closure is one of the most useful features of JavaScript.

The scope of Python is defined by Module,function,class.

The import of Python can manage dependencies and scopes well, and JavaScript has no native package management mechanism and requires AMD to load dependent JS files asynchronously, Requirejs is a common tool.

Assignment logical operators

JavaScript uses = assignment and has two equal judgments of equality (= =) and congruent (= = =). The other logical operators are && and | |, similar to the C language.

Python does not have the same congruent, or, and with the use of the time and and or, closer to natural language. There is no ternary operator a:b in Python? C, the usual notation is

(A and B) or C

Because there is a certain flaw in this writing, you can also write

B if A else C

An important improvement in Python's assignment operation is that the assignment operation is not allowed to return the result of an assignment, and the benefit of this is to avoid the use of an assignment operation when an equality judgment should be used. Because these two operators are so much alike, they are not different from the natural language.

+ + operator

Python does not support the + + operator, so you no longer need to think about the variables in the right and left positions based on the + + symbol, whether it is to add or assign values first, and then add one.

Continuous assignment

With tuples (tuple), Python can assign values to multiple variables at once

(MONDAY, Tuesday, Wednesday, Thursday, FRIDAY, SATURDAY, SUNDAY) = range (7)

function parameters

Python's function parameters support named parameters and optional parameters (providing default values), which is convenient to use, JavaScript does not support optional parameters and default values (can be supported by parsing arguments)

def info (object, spacing=10, collapse=1):

... ...


Call function expression immediately (iife)

A handy feature of JavaScript is the ability to immediately invoke an anonymous function that has just been declared. Others call it self-invoking anonymous functions.

The following code is an example of a module pattern that uses closures to save states for a good encapsulation. This code can be used in situations where reuse is not required.

var counter = (function () {    var i = 0;    return {        get:function () {            return i;            },        Set:function (val) {            i = val;            },        increment: function () {            return ++i;}}        ;    } ());

Python does not have the appropriate support.

Generators and iterators (Generators & Iterator)

In the Python code I'm exposed to, a lot of the patterns of using such generators.

Examples of Python generators

# A generator that yields items instead of returning a listdef firstn (n):    num = 0 while    num < n:        yield n Um        num + = 1    sum_of_first_n = SUM (FIRSTN (1000000))

Some new features of columns are introduced in Javascript1.7, including generators and iterators. However, most browsers do not support these features except Mozilla (Mozilla is basically playing on its own, and the next generation of JavaScript standards should be ECMASCRIPT5).

Examples of Javascript1.7 iterators and generators.

function fib () {  var i = 0, j = 1;  while (true) {    yield i;    var t = i;    i = j;    j + = T;  }}  var g = fib (); for (var i = 0; i < i++) {  console.log ( ());}

List (dictionary, Collection) mapping Expressions (list, Dict, set comprehension)

Python's mapping expressions make it easy to help users construct built-in data types such as lists, dictionaries, collections, and so on.

The following is an example of the use of a list-map expression:

>>> [x + 3 for x in range (4)][3, 4, 5, 6]>>> {x + 3 for x in range (4)}{3, 4, 5, 6}>>> {x:x + 3 For x in range (4)}{0:3, 1:4, 2:5, 3:6}

Javascript1.7 also introduced the array comprehension

var numbers = [1, 2, 3, 4];var doubled = [I * 2 for (I of Numbers)];

Lamda Expressions (LAMDA expression)

The LAMDA expression is an anonymous function based on the well-known lambda calculus. Many languages, such as C#,java, provide support for LAMDA. Pyhton is one of them. JavaScript does not provide native LAMDA support. But there are third-party LAMDA packages.

g = Lambda x:x*3

Adorner (decorators)

Decorator is a design pattern that most languages can support, and Python provides native support for the pattern, a convenience for programmers.

The usage of decorator is as follows.

@classmethoddef foo (arg1, arg2):    ....
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.