Summary of basic knowledge of python and interview questions 1

Hello everyone, I am Wei Xue AI. Today I will introduce the basic knowledge of python and the summary of interview questions. After reading it, it will be of great help to consolidate python.
insert image description here

  1. Multithreading in Python:

Multithreading refers to running multiple threads in a program at the same time to improve the execution efficiency of the program. Modules in Python threadingprovide multithreading support. Thread is the smallest execution unit in the operating system. They share the memory space of the process, but have their own stack space.

  1. Python mutex and deadlock:

A mutual exclusion lock (Mutex) is a synchronization primitive used to protect access to shared resources and prevent simultaneous access by multiple threads. A deadlock is a situation in which two or more threads are waiting for each other to release resources, making it impossible to continue execution.

  1. Lambdas in Python:

Lambda is an anonymous function in Python that simplifies code and makes it more readable. The syntax of a Lambda function is very simple, you only need to use the lambda keyword to define it. Here are a few examples of Lambda functions:
Calculate the sum of two numbers and return the result

add = lambda x, y: x + y
print(add(2, 3)) # 输出 5

This Lambda function takes two parameters x and y, calculates their sum, and returns the result.

  1. Python's deep copy and shallow copy:

Shallow copy refers to creating a new object, but only copying the reference of the original object. Deep copy refers to creating a new object and recursively copying all elements of the original object and its sub-elements. copyModule provides copy()(shallow copy) and deepcopy()(deep copy) methods.

  1. Can Python multithreading use multiple CPUs:

Python multithreading cannot make full use of multiple CPUs, because the Global Interpreter Lock (GIL) restricts execution to only one thread at a time. To take full advantage of multi-core CPUs, multiprocessingmodules can be used to implement multiprocessing.

  1. Python garbage collection mechanism:

Python uses reference counting and a cyclic garbage collector to manage memory. When an object's reference count reaches 0, it is garbage collected. The cyclic garbage collector is used to detect and reclaim objects in reference cycles.

  1. Generators in Python:

A generator is a special kind of iterator that uses yielda keyword to return a value. Generator functions return a new value each time they are called, while preserving the state of the function's execution so that the next time it is called, execution continues where it left off.

  1. The difference between iterators and generators:

An iterator is an object that implements __iter__()the and __next__()method for traversing the elements in a container. A generator is a special kind of iterator that uses yieldkeywords to return values, has a cleaner syntax and is more memory efficient.

  1. The usage and difference of del, remove and pop of Python list:

delis a statement that deletes an element or slice from a list; remove()a method that deletes the first matching element in a list; pop()a method that deletes and returns the element at the specified index (the last element by default).

  1. What is a closure in Python:

A closure is a nested function that captures and remembers the values ​​of local variables of the outer function, even after the outer function has exited.

  1. Python decorators:

The essence of a decorator is a Python function or class, which can be used to wrap other functions or classes and make it have specific behaviors, such as modifying its input and output, checking its errors, adding logging, caching call results, etc. The process defined by the decorator usually needs to use the @ symbol to apply it to the target function or class. When the target function or class is called, the decorator will automatically take effect.

  1. The difference between yield and return in Python:

returnUsed to return a value from a function and terminate the execution of the function; yieldused to return a value from a generator function while retaining the execution state of the function so that the next call continues from where it left off last time.

  1. The underlying implementation of set in Python:

The implementation in Python setis based on a hash table. A hash table is a data structure that uses a hash function to map keys to buckets. setElements in must be hashable.

  1. The difference between a dictionary and a set in Python:

A dictionary is a collection of key-value pairs, and the key must be unique; a set is an unordered, non-repeating collection of elements. Their underlying implementations are all based on hash tables.

  1. The difference between init and new and call in Python:

__init__()It is the initialization method of the class, which is used to set the properties of the object; __new__()it is the construction method of the class, which is used to create and return a new object instance; __call__()it is the callable method of the class, so that the instance of the class can be called like a function.

  1. Python memory management:
    Python memory management includes memory allocation, reference counting, garbage collection, etc. The memory allocator is responsible for allocating and freeing memory; the reference count is used to track the number of references to an object; the garbage collector is responsible for reclaiming objects that are no longer in use.

  2. The difference between a class method and a static method in Python:
    a class method is a @classmethodmethod that uses a decorator, and its first parameter is the class itself (usually named cls); a static method is a @staticmethodmethod that uses a decorator, which does not accept special The first argument (i.e. no selfor clsargument). Class methods can be overridden by subclasses, while static methods cannot.

  3. Methods for traversing dictionaries:
    You can use the items(), keys()and values()methods to iterate over the key-value pairs, keys, and values ​​of a dictionary.

d = {
    
    'a': 1, 'b': 2, 'c': 3}
for key, value in d.items():
    print(key, value)
for key in d.keys():
    print(key)
for value in d.values():
    print(value)
  1. Error and exception handling in Python: errors are programming problems, such as syntax errors; exceptions are program runtime problems, such as dividing by zero. Exception handling uses trythe and exceptstatement to catch and handle exceptions.

  2. The difference between try else and finally in Python:
    elsethe clause tryis executed when the block does not throw an exception; finallythe clause tryis executed regardless of whether the block throws an exception.

  3. The difference between is and == in Python:
    iscompare the identities (memory addresses) of two objects, and ==compare the values ​​of two objects.

  4. The difference between gbk and utf8:
    GBK is a simplified Chinese character encoding, which contains all Chinese characters; UTF-8 is a general character encoding, which contains almost all characters in the world.

  5. Ways to reverse a list:
    You can use reverse()methods or slice operations.

lst = [1, 2, 3, 4, 5]
lst.reverse()
print(lst)
lst = [1, 2, 3, 4, 5]
lst = lst[::-1]
print(lst)
  1. How to convert tuples to dictionaries: A function
    can be used dict()to convert a list of tuples containing key-value pairs into a dictionary.
tuples = [('a', 1), ('b', 2), ('c', 3)]
d = dict(tuples)
print(d)

25. The method of passing function call parameters:
Parameter passing in Python is passed by object reference.

  1. __init__.pyThe role and meaning of the file: __init__.pyThe file indicates that a directory is a Python package, which can contain the initialization code of the package or define __all__variables to control from package import *the behavior.

  2. Several ways to deduplicate lists: you can use collections, list comprehensions or collections.OrderedDict.

#方法1
lst = [1, 2, 2, 3, 3, 4, 4, 5]
unique_lst = list(set(lst))
unique_lst = [x for i, x in enumerate(lst) if x not in lst[:i]]
#方法2
from collections import OrderedDict
unique_lst = list(OrderedDict.fromkeys(lst).keys())
  1. Common list comprehensions in Python:
    List comprehensions are a concise way to create lists, eg [x**2 for x in range(10) if x % 2 == 0].

  2. map and reduce functions:
    map()function applies a function to all elements of a sequence; reduce()function applies a function to the elements of a sequence, from left to right, in order to reduce the sequence to a single value.

  3. The role and usage of except:
    exceptThe clause is used to catch and handle tryexceptions thrown in the block.

try:
    1 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
  1. What is an assertion in Python:
    An assertion is a debugging aid that is used to check whether a certain condition of a program is true. assertThe statement will throw an exception if the condition is false AssertionError.

  2. How to understand characters in strings in Python:
    A string in Python is an immutable sequence of Unicode characters.

  3. How Python performs type conversion:
    Python provides built-in functions (such as int(), float(), str()etc.) for type conversion.

34. Ways to improve the efficiency of Python operation:
use built-in functions and standard libraries, avoid global variables, use local variables, use list comprehensions, use generators, use multi-threading or multi-processing, use C extensions, etc.

Guess you like

Origin blog.csdn.net/weixin_42878111/article/details/131036454