Let's talk about Python eight-part essay
Hello comrades, today I will take you to review the basic issues in python. We all know that python is an interpreted language, and its efficiency is lower than that of other languages. This lower rate is just slightly lower in operation. , but, in many scenarios, buying these is trivial
With the easy to understand and learn the syntax, more work can be completed in a short time, and the development efficiency will also become Higher
At the same time, python comes with various ready-made libraries for us to use in developing programs, and python is also easier to maintain
Python provides us with The very complete basic code base covers a large number of contents such as network, files, GUI, database, text, etc. It is vividly called "batteries included". Developed in Python, many functions do not need to be written from scratch, just use ready-made ones.
In addition to the built-in libraries, Python also has a large number of third-party libraries, which are things developed by others for you to use directly. Of course, if the code you develop is well encapsulated, it can also be used as a third-party library for others to use.
#What is a Python generator?
generator, there are two ways to generate generator objects: one is list generation with parentheses:
g1 = (x for x in range(10) )
One is to include the yield keyword in the function definition:
def fib(max): n, a, b = 0, 0, 1 while n < max:yield b a, b = b, a + b n = n + 1 return 'done'g2 = fib(8)
For generator objects g1 and g2, you can continuously obtain the value of the next element through next(g1) , if there are no more elements, an error StopIteration
will be reported. The value of the element can also be obtained through a for loop.
The advantage of the generator is that it does not take up a lot of memory, you only need to calculate the value of the element when using it.
What is a Python iterator?
What can be used in for loops in Python is called iterable Iterable, including list/set/tuple/str/dict and other data structures and generators; you can use the following statement to judge an object Whether it is iterable:
from collections import Iterableisinstance(x, Iterable)
Iterator Iterator refers to a generator that can be called by the next() function and continuously returns the next value until StopIteration; They are all Iterators, but data structures such as lists are not;
You can turn the list into an Iterator through the following statement:
iter([1,2,3,4,5])
Generators are all Iterators, but iterators are not necessarily generators.
What is the difference between list and tuple?
- list has variable length, but tuple is immutable;
- The value of elements in list can be changed, but tuple cannot;
- list support Append; insert; remove; pop and other methods are not supported by tuple
How are list and dict implemented in Python?
List: It is essentially a sequential list, but the expansion of the table is exponential every time. Therefore, when data is dynamically added and deleted, the physical structure of the table will not change frequently, and at the same time, it will benefit from the sequence. The high efficiency of table traversal (calculating the position of the target element through the corner subscript and the physical address of the table header) makes the overall performance of Python's list relatively excellent
dict: It is essentially a sequential list. However, the index of the storage location of each element is not determined by the order of insertion, but is dynamically generated by the key through the hash algorithm and other mechanisms. That is, the key is hashed through hashing to generate the location where the value should be stored, and then stored. This value; so the query time complexity of dict is O (1);
Therefore, the key of dict can only be a hashable object, that is, an immutable type;
Can multi-core CPUs be used together using multi-threading in Python?
There is something called Global Interpreter Lock (GIL) in Python, which will ensure that only one of your multiple threads is executed at any time.
The execution speed of threads is very fast, which will make you mistakenly think that threads are executed in parallel, but in fact they are all executed in turn. After the GIL level processing, the execution overhead will be increased.
Multi-core tasks can be achieved through multiple processes.
The difference between py3 and py2
print is a function in py3, but just a keyword in py2
The default encoding of py3 files is utf8, and the default encoding of py2 files is ascii
The str of py3 is a unicode string, and the str of py2 is bytes
py3's range() returns an iterable object, py2's range() returns a list, xrange() returns an iterable object, py3's division returns float, py2's division returns int
Variable objects and immutable objects
Variable objects: list, dict, set
Immutable objects: bool, int, float, tuple, str...
The difference between iterators and iterable objects
Iterable objects Class, you must customize the __iter__() magic method. The instantiated objects of the range and list classes are all iterable objects
Iterator class, you must customize __iter__() and _ _next__() magic method, you can use the iter() function to create an iterator of iterable objects
Closure
A closure is an embedding A set of functions, its internal function uses the variables or parameters of the external function, and its external function returns the internal function
可以保存外部函数内的变量,不会随着外部函数调用完而销毁
什么是装饰器?
装饰器是一个接收函数作为参数的闭包函数
它可以在不修改函数内部源代码的情况下,给函数添加额外的功能
import time def calc_time(func): def inner(): t1 = time.time() func() t2 = time.time() print('cost time: {}s'.format(t2-t1)) return inner
什么是元类? 使用场景
元类是创建类的类,type还有继承自type的类都是元类
作用: 在类定义时(new, init)和 类实例化时(call) 可以添加自定义的功能
使用场景: ORM框架中创建一个类就代表数据库中的一个表,但是定义这个类时为了统一需要把里面的类属性全部改为小写,这个时候就要用元类重写new方法,把attrs字典里的key转为小写
GIL(Global Interpreter Lock)
全局解释器锁
全局解释器锁(Global Interpreter Lock)是计算机程序设计语言解释器用于同步线程的一种机制,它使得任何时刻仅有一个线程在执行。
即便在多核处理器上,使用 GIL 的解释器也只允许同一时间执行一个线程,常见的使用 GIL 的解释器有CPython与Ruby MRI。可以看到GIL并不是Python独有的特性,是解释型语言处理多线程问题的一种机制而非语言特性。
GIL的设计初衷?
单核时代高效利用CPU, 针对解释器级别的数据安全(不是thread-safe 线程安全)。首先需要明确的是GIL并不是Python的特性,它是在实现Python解析器(CPython)时所引入的一个概念。
当Python虚拟机的线程想要调用C的原生线程需要知道线程的上下文,因为没有办法控制C的原生线程的执行,所以只能把上下文关系传给原生线程,同理获取结果也是线 程在python虚拟机这边等待。那么要执行一次计算操作,就必须让执行程序的线程组串行执行。
为什么要加在解释器,而不是在其他层?
展开 GIL锁加在解释器一层,也就是说Python调用的Cython解释器上加了GIL锁,因为你python调用的所有线程都是原生线程。原生线程是通过C语言提供原生接口,相当于C语言的一个函数。
你一调它,你就控制不了了它了,就必须等它给你返回结果。只要已通过python虚拟机 ,再往下就不受python控制了,就是C语言自己控制了。
加在Python虚拟机以下加不上去,只能加在Python解释器这一层。
GIL的实现是线程不安全?为什么?
python2.x和3.x都是在执行IO操作的时候,强制释放GIL,使其他线程有机会执行程序。
Python2.x Python使用计数器ticks计算字节码,当执行100个字节码的时候强制释放GIL,其他线程获取GIL继续执行。ticks可以看作是Python自己的计数器,专门作用于GIL,释放后归零,技术可以调整。
Python3.x Python使用计时器,执行时间达到阈值后,当前线程释放GIL。总体来说比Python3.x对CPU密集型任务更好,但是依然没有解决问题。
什么是 lambda 表达式?
简单来说,lambda表达式通常是当你需要使用一个函数,但是又不想费脑袋去命名一个函数的时候使用,也就是通常所说的匿名函数。
lambda表达式一般的形式是:关键词lambda后面紧接一个或多个参数,紧接一个冒号“:”,紧接一个表达式
什么是深拷贝和浅拷贝?
赋值(=),就是创建了对象的一个新的引用,修改其中任意一个变量都会影响到另一个。
浅拷贝 copy.copy:创建一个新的对象,但它包含的是对原始对象中包含项的引用(如果用引用的方式修改其中一个对象,另外一个也会修改改变)
深拷贝:创建一个新的对象,并且递归的复制它所包含的对象(修改其中一个,另外一个不会改变){copy模块的deep.deepcopy()函数}
The above is the detailed content of Let's talk about Python eight-part essay. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Golang is more suitable for high concurrency tasks, while Python has more advantages in flexibility. 1.Golang efficiently handles concurrency through goroutine and channel. 2. Python relies on threading and asyncio, which is affected by GIL, but provides multiple concurrency methods. The choice should be based on specific needs.

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

The key to running Jupyter Notebook in VS Code is to ensure that the Python environment is properly configured, understand that the code execution order is consistent with the cell order, and be aware of large files or external libraries that may affect performance. The code completion and debugging functions provided by VS Code can greatly improve coding efficiency and reduce errors.
