Comparison between Python and Javascript

Source: Internet
Author: User
Compared with Javascript, Python has recently started to develop some Python things due to work needs. Since Javascript has been used for a long time, it will unconsciously use some Javascript Concepts, syntaxes, and so on, it often falls into a trap. I think it is necessary to summarize the differences between Javascript and Python.

Basic concepts

Python and Javascript are both scripting languages, so they have many common features that require interpreters to run. they are both dynamic and support automatic memory management and can both call eval () to execute scripts.

However, they are also quite different. Javascript was originally designed as a client scripting language and is mainly used in browsers. Its Syntax mainly draws on C, because of its elegant, clear, and simple design, Python is widely used in different scenarios such as education, scientific computing, and web development.

Programming paradigm

Both Python and Javascript support a variety of different programming paradigms, which differ greatly in object-oriented programming. Javascript object-oriented is based on prototype, and object inheritance is created by prototype (also object, objects created from a prototype object inherit the methods on the prototype chain. Python is a well-defined class-based inheritance that naturally supports polymorphism (polymophine ).

OO in Pyhton

Class Employee: 'common base class for all employees 'empCount = 0 # class member def _ init _ (self, name, salary): self. name = name self. salary = salary Employee. empCount + = 1 def displayCount (self): print "Total Employee % d" % Employee. empCount def displayEmployee (self): print "Name:", self. name, ", Salary:", self. salary # Create an instance ea = Employee ("a", 1000) eb = Employee ("B", 2000) OO in every criptvar empCount = 0; // Constructor function Employee (name, salary) {this. name = name; this. salary = salary; this. empCount + = 1;} Employee. prototype. displayCount = function () {console. log ("Total Employee" + empCount);} Employee. prototype. displayEmployee = function () {console. log ("Name" + this. name + ", Salary" + this. salary);} // Create an instance var ea = new Employee ("a", 1000); var eb = new Employee ("B", 2000 );

Because it is based on object inheritance, in Javascript, we have no way to use class member empCount, so we have to declare a global variable. of course, in actual development, we will use a more appropriate scope. Note that the new keyword is required to create objects in Javascript, but not in Python.

Apart from native prototype-based inheritance, there are also many Javascript OO tools that use closures or prototypes to simulate class inheritance. we will not discuss this because it is not a property of the language itself.

Thread model

In the Javascript world, there is no concept of multithreading. in concurrency, the event-driven approach is used. all JavaScript programs run in one thread. Web worker can be used to concurrently process tasks in HTML5, but it does not change the limit of Javascript single-thread.

Python supports multithreading through the thread package.

Immutable type)

In Python, some data types cannot be changed, which means that data of this type cannot be modified, and all modifications will return new objects. All data types in Javascript can be changed. Python introduces unchangeable types. I think it is to support thread security. Javascript is a single-threaded model, so there is no need to introduce unchangeable types.

Of course, in Javascript, the attribute of an object can be defined as read-only.

var obj = {};Object.defineProperty(obj, "prop", {    value: "test",    writable: false});

In support of ECMAScript5, you can also call the freeze method of the Object to make the Object unmodifiable.

Object. freeze (obj)

Data type

Javascript data types are relatively simple, including object, string, boolean, number, null, and undefined. a total of six types

In Python, everything is an object, such as module, function, and class.

Python has five built-in simple data types: bool, int, long, float, and complex, as well as the container type, code type, and internal type.

Boolean

Javascript supports true and false. Python supports True and False. They have no difference except case sensitivity.

String

Javascript uses UTF16 encoding.

Python uses ASCII codes. Encode and decode must be called for encoding conversion. You can use u as the prefix to specify that the string is Unicode encoded.

Value

All numeric types in Javascript are implemented as 64-bit floating point numbers. Supports NaN (Not a number) and positive and negative infinity (+/-Infiity ).

Python has many numeric types, among which the plural type is very convenient, so it is very popular in the field of scientific research and education. This is also one of the reasons. NaN is not defined in Python. division by zero causes an exception.

List

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

The List of Python is similar to the Array of Javascript, while the Tuple can be considered as an unchangeable List.

Apart from using the built-in method len in Python, Javascript and Python provide similar methods to operate the list. In Python, the list objects are very flexible and convenient, which is not available in Javascript. For example, l [5:-1], l [: 6], and so on.

Dictionary, hash table, and object

A large number of objects are created using {} in Javascript. these objects are no different from dictionaries. you can use [] or. to access object members. You can dynamically add, modify, and delete members. It can be considered that the object is a Javascript dictionary or hash table. The object key must be a string.

Python has a built-in hash table (dictS). Unlike Javascript, dictS can have various types of key values.

Null value

Javascript defines two null values. Undefined indicates that the variable is not initialized. null indicates that the variable has been initialized but the value is null.

No uninitialized value exists in Python. if a variable value is empty, 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 above code, v1 is a global variable, not initialized; its value is undefined; v2 is a global variable, and its initialization is null; v3 is a local uninitialized variable, v4 is a variable whose local initialization is null; v5 is a variable whose local initialization is a character.

Declaration and initialization of variables in Python

V1 = None

V2 = 'someting'

Variable Declaration and initialization in Python are much simpler. When accessing a non-existent variable in Python, a NameError exception is thrown. If the value of the Accessed object or dictionary does not exist, AttributeError or KeyError is thrown. Therefore, it is necessary to determine whether a value exists in Javascript and Python in a different way.

Check the existence of a variable in Javascript:

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

Be sure to use it! V to check whether v initialization is ambiguous because there are many situations! All values return true.

Check the existence of a variable in Python:

try:    vexcept NameError    ## do something if v does not exist

In Python, you can also check whether the variable exists in local locals () or global globals () to determine whether the variable exists.

Type check

Javascript can use typeof to obtain the type of a variable:

Example of typeof in Javascript:

typeof 3 // "number"typeof "abc" // "string"typeof {} // "object"typeof true // "boolean"typeof undefined // "undefined"typeof function(){} // "function"typeof [] // "object"typeof null // "object"

Be very careful when using typeof. from the above example, you can see that typeof null is actually an object. Because of the weak type feature of javscript, to obtain more practical types, you must also use instanceof, constructor, and other concepts. For details, refer to this article

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

>>> type([]) is listTrue>>> type({}) is dictTrue>>> type('') is strTrue>>> type(0) is intTrue

You can also use isinstance () to determine the class type.

class A:    passclass B(A):    passisinstance(A(), A)  # returns Truetype(A()) == A      # returns Trueisinstance(B(), A)    # returns Truetype(B()) == A        # returns False

However, note that the class style of Python has changed once. not all versions of Python run the same code. in the old style, the type of all instances is 'instance ', therefore, using the type method to check is not a good method. This is similar to Javascript.

Automatic type conversion

When different types of operations are operated together, Javascript always performs automatic type conversion as much as possible, which is convenient and error-prone. Especially when performing Numeric and string operations, errors may occur accidentally. I used to calculate various numeric attributes in SVG, such as x and y coordinates. when you accidentally add a string to a numeric value, javascript will automatically convert a value, often NaN, so that SVG cannot be drawn at all, because automatic conversion is legal and it is very difficult to locate the error.

Python is very cautious at this point and generally does not perform automatic conversion between different types.

Syntax

Style

Python uses indentation to determine the end of the logical line. This may be the most unique attribute of Python. of course, some people have some slight terms about it, especially when you need to modify and refactor the code, modifying indentation often causes a lot of trouble.

Although Javascript has Java in its name, its style is also a bit like Java, but it and Java are like reifeng tower and Lei Feng, there is really no relationship between half a dime. Then the syntax is similar to that of C. It must be mentioned that coffeescript, as a language built on top of Javascript, adopts a syntax style similar to Python and uses indentation to determine the logical line.

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]) ;}}

The above two code examples show that Python is indeed very concise.

Scope and Package management

The Javascript scope is defined by the method function, that is, the same scope exists within the same method. This is a serious difference 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, and class.

Python import can well manage dependencies and scopes, while Javascript does not have a native package management mechanism. it needs to use AMD to asynchronously load dependent js files. requirejs is a common tool.

Value assignment logic operator

Javascript uses the = value assignment function and has two equal judgments: equal (=) and full (=. Other logical operators include & |, which is similar to the C language.

Python does not have full equality, or is closer to natural languages than and or in use. Python does not have A: B? C. The General syntax is

(A and B) or C

Because such writing has some defects, you can also write

B if A else C

An important improvement of the value assignment operation in Python is that the value assignment operation is not allowed to return the value assignment result. the advantage of this operation is that the value assignment operation should be used incorrectly when the value assignment operation should be used. These two operators are very similar, and there is no difference in natural language.

++ Operator

Python does not support the ++ operator. Yes, you no longer need to consider whether to add repeated values first or add a value first based on the ++ symbol in the left and right positions of the variable.

Continuous assignment

Using tuple, Python can assign values to multiple variables at a time.

(MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY) = range (7)

Function parameters

Python function parameters support named parameters and optional parameters (default values are provided), which are easy to use. Javascript does not support optional parameters and default values (which can be supported by parsing arguments)

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

......

Others

Call function expression (IIFE) now)

One convenient feature of Javascript is that it can immediately call an declared anonymous function. Some people call it self-called anonymous functions.

The following code is an example of the module mode. closure is used to save the state for good encapsulation. Such code can be used without reuse.

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

Python does not support it.

Generators & Iterator)

In the Python code I have come into contact with, a large number of such generator modes are used.

Python generator example

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

New columns are introduced in Javascript1.7, including generators and iterators. However, most browsers except Mozilla (Mozilla is basically playing on its own, and the next-generation Javascript standard is ECMAScript5) do not support these features.

Example of Javascript1.7 iterator and generator.

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 < 10; i++) {  console.log(g.next());}

List (dictionary, Set) ing expressions (List, Dict, Set Comprehension)

Python ing expressions help you easily construct built-in data types such as lists, dictionaries, and collections.

The following is an example of the list ing 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}

Cript1.7 also introduced Array Comprehension.

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

Lamda Expression (Lamda Expression)

The Lamda expression is an anonymous function based on the famous lambda algorithm. Many languages such as C # and Java provide lamda support. Pyhton is one of them. Javascript does not provide native Lamda support. However, there are third-party Lamda packages.

G = lambda x: x * 3

Decorators)

Decorator is a design mode. most languages support this mode. Python provides native support for this mode, which is a convenient tool for programmers.

The Decorator usage 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: info-contact@alibabacloud.com 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.