Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the common interview questions in Python?

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "what are the common interview questions in Python". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. One line of code to realize the sum of 1Mutual 100

Summation by using sum () function

2. How to modify global variables within a function

The function internal global declaration modifies the global variable

3. List 5 python standard libraries

Os: provides a number of functions associated with the operating system

Sys: commonly used for command line arguments

Re: regular matching

Math: mathematical operation

Datetime: processing date time

4. How to delete keys and merge two dictionaries

Del and update methods

5. Talk about the GIL of python

GIL is the global interpreter lock of python. If there are multiple threads running in the same process, a thread will occupy the python interpreter (adding a lock that is GIL) when running the python program, so that other threads in the process can not run until the thread finishes running. If a thread encounters a time-consuming operation while running, the interpreter unlocks it and causes other threads to run. So in multithreading, threads still run sequentially, not at the same time.

In multi-processes, because each process can be allocated resources by the system, which is equivalent to each process has a python interpreter, so multi-processes can run multiple processes at the same time, but the disadvantage is that the process system resources are expensive.

6. The method of removing duplicates of list by python

First through the collection to repeat, in the rotation list.

7. What does "args,**kwargs" in fun (* args,**kwargs) mean?

8. The difference between range of python2 and python3

Python2 returns a list, and python3 returns an iterator to save memory.

9. Explain in a sentence what kind of language can use decorators?

Functions can be passed as arguments, and decorators can be used.

10. What are the built-in data types of Python

Integer-int

Boolean type-bool

String-str

List-list

Tuple-tuple

Dictionary-dict

11. Briefly describe the difference between _ _ new__ and _ _ init__ in object-oriented

_ _ init__ is the initialization method. After the object is created, it is called by default and can receive parameters, as shown in the figure:

(1) _ _ new__ must have at least one parameter, cls, that represents the current class, which is automatically identified by the Python interpreter when instantiated.

(2) _ _ new__ must have a return value and return the instantiated instance. You should pay special attention to this when you implement _ _ new__. You can return the instance from the parent class (via super (current class name, cls)) _ _ new__, or directly from the _ _ new__ of object.

(3) _ _ init__ has a parameter self, which is the instance returned by this _ _ new__. _ _ init__ can complete some other initialization actions on the basis of _ _ new__, and _ _ init__ does not need to return a value.

(4) if _ _ new__ creates an instance of the current class, the _ _ init__ function is called automatically. The current class instance is guaranteed by using the * argument of the _ _ new__ function called in the return statement as cls, if it is the class name of another class. Then the actual creation returns instances of other classes. In fact, the _ _ init__ function of the current class will not be called, and the _ _ init__ function of other classes will not be called.

12. Briefly describe what the with method has done to open the processing file for us?

There may be some anomalies when opening a file for reading and writing, if you follow the normal f.open.

In writing, we need try,except,finally to make exception judgment, and no matter what happens in the file, we have to execute finally f.close () to close the file. The with method helps us to implement f.close in finally.

(of course, there are other custom features. If you are interested, you can study the source code of with method.)

13. List [1, map 2, 3, 4, and 5]. Please use the function to output [1, 4, 9, 16, 25], and use the list derivation to extract numbers greater than 10, and finally output [16525].

The * parameter of the map () function is fun, the second parameter is general list, and the third parameter may or may not be written as list, depending on the requirement:

14. The method of generating random integers, random decimals and 0 decimals in python

Random integers: random.randint (aformab) to generate integers in the interval

Random decimals: use numpy library to generate 5 random decimals using np.random.randn (5)

0-1 random decimal: random.random (), no parameters are passed in parentheses

15. Avoid escaping the string. Which letter represents the original string?

R, indicating that the original string is required and special characters are not escaped

16. China, use regular matching to match the content in the tag ("China"), in which the class name of class is uncertain.

17. Examples of python interrupt method

Assert () method, if the assertion is successful, the program continues to execute, and if the assertion fails, the program reports an error:

18. The data table student has an id,name,score,city field, in which the name in name may be duplicated, and the duplicate rows need to be eliminated. Please write a sql statement

Select distinct name from student

19. 10 common Linux commands

Ls pwd cd touch rm mkdir tree cp mv cat more grep echo

20. The difference between python2 and python3? List 5

(1) Python3 must print content in parentheses when using print, such as print ('hi').

Python2 can use either parentheses or a space to separate the printed content, such as print 'hi'

(2) python2 range returns the list, and iterator in python3 saves memory.

(3) ascii coding is used in python2 and utf-8 coding is used in python.

(4) unicode represents string sequence and str represents byte sequence in python2

In python3, str represents a string sequence and byte represents a byte sequence.

(5) for normal display of Chinese in python2, introduce coding declaration, which is not required in python3.

(6) the raw_input () function in python2 and the input () function in python3

21. List the variable data types and immutable data types in python, and briefly describe the principle

Immutable data types: numeric, string string, and tuple tuple

The value of the variable is not allowed to change. If you change the value of the variable, it is equivalent to creating a new object, but for an object with the same value, there is only one object (an address) in memory. The following figure uses the id () method to print the id of the object.

Variable data types: list list and dictionary dict

Allow the value of the variable to change, that is, if you only change the value of the variable after append, + =, etc., instead of creating a new object, the address of the object referenced by the variable will not change, but for different objects with the same value, there will be different objects in memory, that is, each object has its own address, which is equivalent to saving multiple copies of objects with the same value in memory. There is no reference count, it is a real object.

22, s = "ajldjlajfdljfddd", remove duplicates and sort "adfjl" from small to large

Set de-weight, de-re-converted to list, using the sort method to sort, reeverse=False is from small to large

List is an immutable data type, and there is no return value for s.sort, so the comments are written incorrectly.

23. Multiply two numbers with lambda function

24. The dictionary sorts from smallest to largest according to the key.

Dic= {"name": "zs", "age": 18, "city": "Shenzhen", "tel": "1362626627"}

25. Use the Counter method of collections library to count the number of occurrences of each word in a string.

"kjalfj;ldsjafl;hdsllfdhg;lahfbl;hl;ahlf;h"

26. The string a = "not 404 found Zhang San 99 Shenzhen". There is a space in the middle of each word. Filter out English and numbers with rules, and finally output "Zhang San Shenzhen".

By the way, paste the code that matches the decimal, although it can match, but the robustness needs to be further confirmed.

27. The filter method finds all the odd numbers of the list and constructs a new list

A = [1,2,3,4,5,6,7,8,9,10]

The filter () function is used to filter sequences, filter out elements that do not meet the criteria, and return a new list of eligible elements. This receives two parameters, * as a function, and the second as a sequence. Each element of the sequence is passed as a parameter to the function for judgment, and then returns True or False,*** to put the elements that return True into the new list.

28. List derivation to find all odd numbers in the list and construct a new list, a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

29. Regular re.complie function

Re.compile is about compiling regular expressions into an object, speeding up and reusing

What type of data are 30, a = (1,) b = (1), c = ("1") respectively?

31. Two lists [1, 5, 7, 9] and [2, 2, 2, 6, 8] are merged into [1, 2, 2, 3, 6, 7, 8, and 9].

Extend can add elements from another collection to the list one by one, unlike append as a whole.

32. Delete files with python and delete files with linux command

Python:os.remove (file name)

Linux: rm file name

33. In the log log, we need to record the occurrence time of error,warning and so on with a timestamp.

Please use the datetime module to print the current timestamp "2018-04-01 11:38:54"

By the way, the code of the week was also posted.

34. Database optimization query method

Foreign keys, indexes, federated queries, select specific fields, etc.

35. Please list the open source library drawn by any kind of statistical chart you know (bar chart, line chart, etc.)

A third party is also fine.

Pychart 、 matplotlib

36. Write a custom exception code

Custom exceptions throw exceptions with raise

37. In regular expression matching, what is the difference between (. *) and (. *?) matching?

(. *) is a greedy match, which will match as many future matches as possible that satisfy the regularity.

(. *?) is a non-greedy match, which will match as few matches as possible that satisfy the regularity.

38. Briefly describe the orm of Django

ORM, full spelling Object-Relation Mapping, means object-relational mapping.

The data model can be decoupled from the database, and the database can be easily replaced through simple configuration, without the need to modify the code, only object-oriented programming is needed. Orm operations are essentially translated into corresponding sql statements according to the docking database engine. All projects developed with Django do not need to care about the underlying use of MySQL, Oracle, sqlite...., if the database is migrated. You only need to change the database engine of Django.

39. [1, 2], [3, 4], [5, 6] one line of code expands the list and gets [1, 2, 3, 4, 5, 6]

List-driven coquettish operation

The running process: for i in a, each I is [1rect 2], [3pr 4], [5je 6], for j in i, each j is 1Magne, 2pm, 4pm, 5pm 6, and the result is the merger.

There is a more coquettish way, the list into numpy matrix, through numpy's flatten () method, the code is always more coquettish, not the most coquettish

40, x = "abc", y = "def", z = ["d", "e", "f"], find the results returned by x.join (y) and x.join (z), respectively

Inside the join () parentheses are iterable objects, and x is inserted into the middle of the iterable objects to form a string. The results are consistent, and there is no sudden feeling that the common operations of the string will not play.

By the way, I suggest you learn the os.path.join () method, the stitching path is often used, and join is also used. What's the difference between join and string operation? you can consult the relevant documentation for this question. There will be an answer later.

41. Give an example to illustrate the significance of try except else finally in the exception module.

Try..except..else did not catch an exception, execute the else statement

Try..except..finally executes finally statements regardless of whether an exception is caught or not

42. Exchange two values in python

43. Give an example to illustrate the usage of the zip () function

The zip () function returns a list of tuples with one or more sequences (iterable objects) as arguments. At the same time, the elements in these sequences are matched side by side.

The zip () parameter can accept any type of sequence, and it can also have more than two parameters; when the length of the input parameter is different, zip can automatically intercept according to the shortest sequence length to obtain tuples.

44, a = "Zhang Ming 98 points", replace 98 with 100 with re.sub

45. Write 5 commonly used SQL statements

Show databases

Show tables

Desc table name

Select * from table name

Delete from table name where id=5

Update students set gender=0,hometown= "Beijing" where id=5

46, a = "hello" and b = "Hello" are encoded as bytes types

47. What is the result of [1Jing 2jue 3] + [4JR 5je 6]?

The addition of two lists is equivalent to extend

48. Methods to improve the running efficiency of python

(1) use the generator because you can save a lot of memory

(2) cyclic code optimization to avoid excessive repetitive code execution.

(3) Cython PyPy is used in the core module to improve efficiency.

(4) Multi-process, multi-thread and cooperative program

(5) multiple if elif condition judgments can be written in front of the conditions that are most likely to occur first, which can reduce the number of program judgments and improve efficiency.

49. Briefly describe the difference between mysql and redis

Redis: memory non-relational database, the data is stored in memory, the speed is fast.

Mysql: relational database, where the data is stored on disk. If you retrieve it, there will be some Io operations, and the access speed is relatively slow.

50. How to deal with bug

(1) errors in details, printed by print (), can be executed to print () indicating that there is no problem with the above code, and whether there is a problem with the segmented detection program. If it is js, you can alert or console.log.

(2) if some third-party framework is involved, check the official documents or some technical blogs.

(3) for the summary of the management and classification of bug, the general test records the tested bug with bug management tools such as teambin, and then we will modify it one by one. The process of modification is also a way to understand business logic and improve the rigor of your programming logic. I will also collect and make some notes.

(4) the problem of guide package and the display error caused by city positioning polyphonic words.

51. Regular match, matching date 2018-03-20

Url=' https://sycm.taobao.com/bda/tradinganaly/overview/get_summary.json?dateRange=2018-03-20%7C2018-03-20&dateType=recent1&device=1&token=ff25b109b&_=1521595613462'

Some students still ask the rule, in fact, matching is not difficult. Extract a characteristic sentence and match it with (. *?)

52. List= [2, 3, 5, 5, 4, 4, 9, and 6], sort from small to big, do not use sort, output [2, 3, 5, 4, 4, 5, 5, 6, and 9]

Use the min () method to find the minimum value, delete the minimum value from the original list, add the minimum value to the new list, call the function that gets the minimum value recursively, and operate repeatedly.

53. Write a single-column mode

Because the _ _ new__ method executes when creating an object, and return must return whether the cls.__instance of the instantiated object exists. If not, create the object, and if so, return the object to ensure that only one instance object exists (single column). Print ID with the same value, indicating that the object is the same.

54. Keep two decimal places

The title itself is only a = "% .03f"% 1.3335, so that the result of calculating an is provided with the round method (numerical value, reserved digits) in order to expand the idea of preserving decimals.

55. Find three ways to print the results

Fn ("one", 1) passes the key-value pair directly to the dictionary

Fn ("two", 2) because the dictionary is a variable data type in memory, so pointing to the same address, passing a new amount parameter will be equivalent to adding a key-value pair to the dictionary.

Fn ("three", 3, {}) is no longer the dictionary of the original default parameters because a new dictionary has been passed

56. List common status codes and meanings

200 OK

Normal processing of request completed

204 No Content

The request was processed successfully and no entity principal returned

206 Partial Content

GET scope request processed successfully

301 Moved Permanently

* redirect, the resource has been * assigned a new URI

302 Found

Temporary redirection, the resource has been temporarily allocated a new URI

303 See Other

Temporary redirection, expected to be obtained using GET direction

304 Not Modified

The conditional request sent was not met

307 Temporary Redirect

Temporary redirect, POST will not become GET

400 Bad Request

Request message syntax error or parameter error

401 Unauthorized

Need to pass HTTP authentication, or authentication failed

403 Forbidden

The requested resource was rejected

404 Not Found

The requested resource could not be found (the server has no reason to refuse)

500 Internal Server Error

Server failure or Web application failure

503 Service Unavailable

Server overload or downtime maintenance

57. Explain the performance optimization of web project from front-end, back-end and database respectively.

There are many methods for this topic online. I don't want to take screenshots of the long text on the Internet. I have a headache to read. I will say a few points according to my own understanding:

Front-end optimization:

(1) reduce http requests, such as making sprite diagrams

(2) html and CSS are placed at the top of the page, and javascript is placed at the bottom of the page. Because js loads more slowly than HTML and Css, html and css should be loaded first in case the page is not fully displayed, the performance is poor, and the user experience is poor.

Back-end optimization:

(1) the cache stores data with high times of reading and writing and few changes, such as the information of the home page of the website, the information of goods, and so on. When an application reads data, it usually reads it from the cache first, and then accesses the disk database and writes the data to the cache again if it cannot be read or the data has been invalidated.

(2) Asynchronous mode. If there is a time-consuming operation, you can use async, such as celery.

(3) Code optimization to avoid too many cycles and judgments. If there are multiple if else judgments, priority should be given to the situation that is most likely to happen first.

Database optimization:

(1) if there are conditions, the data can be stored in redis with fast reading speed.

(2) establishing indexes, foreign keys, etc.

58. Delete the "name" field in the dictionary using pop and del, dic= {"name": "zs", "age": 18}

59. List common MYSQL data storage engines

InnoDB: supports transaction processing, foreign keys, crash repair and concurrency control. If you need to have high transaction integrity requirements (such as banks) and concurrency control (such as ticket sales), then choosing InnoDB has a great advantage. If you need to update and delete databases frequently, you can also choose InnoDB because transaction commit (commit) and rollback (rollback) are supported.

MyISAM: fast data insertion, low space and memory usage. If the table is mainly used to insert new records and read records, then selecting MyISAM can achieve high processing efficiency. It can also be used if the application has low requirements for integrity and concurrency.

MEMORY: all the data is in memory, the processing speed of the data is fast, but the security is not high. If you need fast reading and writing speed and low data security requirements, you can choose MEMOEY. It has requirements on the size of the table and cannot create too large a table. Therefore, such databases are only used in relatively small database tables.

60. Calculate the running result of the code, which has been mentioned in the zip function history article, and get [("a", 1), ("b", 2), ("c", 3), ("d", 4), ("e", 5)]

A New method of creating Dictionary by dict ()

61. A brief description of the homologous strategy

The same origin policy needs to meet the following three requirements:

(1) same agreement

(2) the domain name is the same

(3) same port

Different sources of http:www.test.com and https:www.test.com-- different protocols

Different sources of http:www.test.com and http:www.admin.com-- different domain names

Different sources of http:www.test.com and http:www.test.com:8081-- different ports

As long as any of these requirements are not met, the same origin policy will not be met, and "cross-domain" will appear.

62. Briefly describe the difference between cookie and session

(1) session is on the server side and cookie on the client side (browser)

(2) the operation of session depends on sessionid, and sessionid is stored in cookie, that is, if cookie is disabled in the browser, session will also fail, and when storing Session, the key is the same as the sessionid in Cookie, and the value is the key value pair information set by the developer, which is encoded by base64, and the expiration time is set by the developer.

(3) the security of cookie is worse than that of session.

63. Brief introduction of multi-thread and multi-process

Process:

(1) the basic unit of resource allocation and scheduling in the operating system. Multiple processes are independent of each other.

(2) good stability. If one process crashes, it will not affect other processes, but the process consumes a lot of resources, and the number of processes started is limited.

Thread:

(1) the basic unit of resource allocation and scheduling in CPU. A thread is a part of a process and is a smaller basic unit that can run independently than a process. Multiple threads under a process can share all the resources of the process.

(2) if IO operations are intensive, multithreading can be run efficiently. The disadvantage is that if a thread crashes, it will cause the process to crash.

Application:

IO intensive use of multithreading, when the user input, sleep, you can switch to other threads to execute, reducing the waiting time

CPU uses multiple processes intensively, because if IO operates less and uses multithreading, because threads share a global interpreter lock, the currently running thread will occupy GIL, and other threads do not have GIL, so they cannot take full advantage of multicore CPU.

64. Briefly describe the methods of any () and all ()

Any (): true as long as one element in the iterator is true

All (): all judgments in the iterator return true, and the result is true.

What element in python is fake?

Answer: (0, empty string, empty list, empty dictionary, empty tuple, None, False)

Test the all () and any () methods

65. What anomalies do IOError, AttributeError, ImportError, IndentationError, IndexError, KeyError, SyntaxError and NameError represent respectively?

IOError: input / output exception

AttributeError: attempts to access properties that an object does not have

ImportError: unable to introduce modules or packages. It's basically a path problem.

IndentationError: syntax error, code not properly aligned

IndexError: the subscript index exceeds the sequence boundary

KeyError: try to access keys that don't exist in your dictionary

SyntaxError:Python code logic syntax error, cannot execute

NameError: use a variable that has not yet been assigned an object

66. The difference between copy and deepcopy in python

(1) copy immutable data types, no matter copy or deepcopy, are the same address when the value copied shallowly is an immutable object (numeric, string, tuple) and = "assign", the id value of the object is the same as the original value of the shallow copy.

(2) the copied values are mutable objects (lists and dictionaries)

There are two cases of shallow copy copy:

* case: there are no complex sub-objects in the copied object, and the change of the original value will not affect the shallow copied value, and the shallow copied value change will not affect the original value. The id value of the original value is different from that of the shallow copy.

The second case: there are complex sub-objects in the copied object (for example, a child element in the list is a list). Changing the value of the complex sub-object in the original value will affect the shallow copied value.

Deep copy deepcopy: completely replicate independently, including inner lists and dictionaries.

67. List several magic methods and briefly introduce their uses

_ _ init__: object initialization method

The method executed when the object is created by _ _ new__:, which is used in single-column mode

_ _ str__: when using print to output objects, as long as you define the _ _ str__ (self) method, the data from the return in this method will be printed

_ _ del__: method for deleting object execution

68. C:Users y-wu.junyaDesktop > python 1.py 22 33 command line starts the program and passes parameters, what data will print (sys.argv) output?

A list of file names and parameters

69. Please change [i for i in range (3)] to generator

Generators are special iterators

(1) the list expression can be changed into a generator by changing [] to ().

(2) when a function returns worthwhile, yield becomes a generator, not a function.

Just replace the square brackets with parentheses. Are you shocked?

70, a = "hehheh", removing the closing space

71. For example, sort and sorted sort the list, list= [0qimi 1jue 3mai 10mai 5je 9]

72. Sort list foo = [- 5, 8, 0, 4, 4, 9, 9, 4, 4, 5, 20, 2, 2, 4], using lambda function to sort from small to big

73. Use lambda function to sort list foo = [- 5, 8, 0, 0, 4, 9, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,

The output is as follows:

] positive numbers from small to big, negative numbers from big to small.

(pass two conditions, x and > >

Linux allows you to redirect the result of command execution to a file

Output / append the content that should be displayed on the terminal to the specified file

> indicates the output and overwrites the original contents of the file

> > indicates appending, which appends the content to the end of the existing file.

Usage example:

Save the output information of echo to 1.txt echo Hello Python > 1.txt

Append the information output from tree to the end of the 1.txt file tree > > 1.txt

99. Regular expressions match www.itcast.cn

The front and the back correspond, and you can use this method

100. is the python parameter value or address?

In Python, function arguments are passed by reference (note that they are not passed by values). For immutable types (numeric, string, tuple), dependent variables cannot be modified, so the operation does not affect the variable itself, while for variable types (list dictionary), function body operations may change incoming parameter variables.

101. Find the intersection, difference and union of two lists

102. Generate a random number from 0 to 100

Random.random () generates a random decimal between 0 and 1, so multiply it by 100

103. benefits of lambda anonymous functions

Simplify the code, lambda omits defining functions, and map omits the process of writing for loops

104. Common network transport protocols

UDP, TCP, FTP, HTTP, SMTP, etc

105, single quotation mark, double quotation mark, three quotation mark usage

(1) there is no difference between single quotation marks and double quotation marks, but single quotation marks do not need to press shift, typing is slightly faster. When representing a string, you can use double quotes in single quotation marks instead of escaping characters, and vice versa.

'She said: "Yes."' or "She said: 'Yes.'"

(2) but if you enclose the single quotation mark directly, you need to escape, like this:

'She said:'Yes.''

(3) three quotes can be used to write multiple lines directly, usually for long, long strings.

"

Hello

World

"

106. python garbage collection mechanism

Python garbage collection is mainly based on reference counting, supplemented by marking-clearing and generational clearing, in which marking-clearing and generational collection are mainly to deal with the problem of circular references.

Citation counting algorithm

When a variable holds a reference to an object, the reference count of the object is incremented by 1

When using del to delete an object pointed to by a variable, if the reference count of the object is not 1, such as 3, then the reference count will only be subtracted by 1, that is, it will become 2. When del is called again, it will become 1. If del is called again, it will really change the

Object for deletion

107. the difference between get and post in HTTP requests

(1) GET requests request data directly through URL, and the data information can be seen directly in URL, such as browser access, while POST requests are placed in the request header and cannot be seen directly.

(2) GET has a limit on data size, which is generally no more than 1024 bytes, and this statement is not entirely accurate. HTTP protocol does not set an upper limit for the length of URL bytes, but the browser does some processing, so the length varies according to different browsers; POST requests are not specified in the HTTP protocol, and generally there is no limit, but in fact, browsers also have default values. Overall, a small amount of data uses GET and a large amount of data uses POST.

(3) because the data parameters are exposed in URL, the security of GET request is relatively low. For example, if the password cannot be exposed, you cannot use GET request. In POST request, the request parameter information is placed in the request header, so it is more secure and can be used. In practice, when it comes to login operations, try to use HTTPS requests for better security.

108. the method of reading Excel file in python

Application data analysis library pandas

109. Brief introduction of multi-thread and multi-process

Process:

1. The basic unit of resource allocation and scheduling in the operating system, in which multiple processes are independent of each other.

2. Good stability. If one process crashes, it will not affect other processes, but the process consumes a lot of resources, and the number of open processes is limited.

Thread:

1. The basic unit of resource allocation and scheduling in CPU. A thread is a part of a process and is a smaller basic unit that can run independently than a process. Multiple threads under a process can share all the resources of the process.

2. If IO operations are intensive, multithreading can be run efficiently. The disadvantage is that if a thread crashes, it will cause the process to crash.

Application:

IO intensive use of multithreading, when the user input, sleep, you can switch to other threads to execute, reducing the waiting time

CPU uses multiple processes intensively, because if IO operates less and uses multithreading, because threads share a global interpreter lock, the currently running thread will occupy GIL, and other threads do not have GIL, so they cannot take full advantage of multicore CPU.

Search and match in python regularization

This is the end of the content of "what are the common interview questions for Python". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report