面试Python高频问题汇总

时间:2022-07-24
本文章向大家介绍面试Python高频问题汇总,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

装饰器

它们封装一个函数,并且用这样或者那样的方式来修改它的行为。

python允许函数作为参数传递(Python里面一切皆对象)

传递一个函数到装饰器函数中,在装饰器函数中实现一个用于装饰的函数,该函数自己做一些操作,并调用传入的函数,最后返回自身。 实际上是一个闭包结构。

可以使用@加装饰器函数来对一个函数实现装饰。

functools.wraps可以解决函数被装饰后__name__变量变成用于装饰的函数的问题。 使用方式 在装饰函数 前+ @wraps(被装饰函数名) 注意:@wraps接受一个函数来进行装饰,并加入了复制函数名称、注释文档、参数列表等等的功能。这可以让我们在装饰器里面访问在装饰之前的函数的属性。

使用场景:日志(Logging) 授权(Authorization)

装饰器类 在一个类的__call__里面实现装饰函数并返回 包裹一个函数和装饰器函数一样@+类名

闭包 在Python中创建一个闭包可以归结为以下三点:

闭包函数必须有内嵌函数 内嵌函数需要引用该嵌套函数上一级namespace中的变量 闭包函数必须返回内嵌函数

闭包可以被理解为一个只读的对象,你可以给他传递一个属性,但它只能提供给你一个执行的接口,这就牵扯到的另一个特性:惰性求值 还有另一种用处:需要对某个函数的参数提前赋值的情况,当然在Python中已经有了很好的解决访问functools.parial, 但是用闭包也能实现。

惰性求值这点,我不是很赞同,下面是我关于闭包的看法。

  • 首先,闭包具有一定程度的封装性,内嵌函数只能通过外层函数的接口传递参数并访问。
  • 其次,内层函数可以使用传递给外层函数的参数以及外层函数里定义在内嵌函数之前的变量。闭包改变了变量的作用域,使得我们可以使用局部变量来完成全局变量的功能,减少了全局变量的使用(JavaScript中闭包的核心用法)。
  • 再者,外层函数本身也可以自己执行一些功能,相当于增加了内嵌函数的功能(装饰器就是通过闭包实现的)。
  • 最后,可以创建多个变量用外层函数赋值,每一个变量所代表的函数都具有独立的参数范围和作用范围。
def outer(a):
    c = 5
    def inner():
        return a + c + 10
    return inner

fun1 = outer(10)
fun2 = outer(20)
fun3 = outer(30)
print(fun1())
print(fun2())
print(fun3()

多线程

多线程有如下优点

  • 使用线程可以把占据时间长的程序中的任务放到后台去处理
  • 用户界面可以更加吸引人,比如用户点击了一个按钮去触发某些事件的处理,可以弹出一个进度条来显示处理的进度。
  • 程序的运行速度可能加快
  • 在一些等待的任务上实现如用户输入、文件读写和网络收发数据等,线程就比较有用了

Thread方法

Python3中支持线程的两个模块:

  • _thread (从Python2中兼容过来,已被废弃,不推荐使用)
  • threading
_thread.start_new_function(function, args[, kwargs])
# function 线程函数
# args 传给线程函数的参数,必须是tuple
# kwargs 可选参数

_thread提供了低级别的、原始的线程以及一个简单的锁,它相比于threading模块的功能还是比较有限的。

threading模块除了包含_thread模块中的所有方法外,还提供的其他方法:

threading.currentThread(): 返回当前的线程变量。 threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。 threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。

Thread类

除了使用方法外,线程模块同样提供了Thread类来处理线程,Thread类提供了以下方法:

run(): 用以表示线程活动的方法。 start():启动线程活动。 join([time]): 等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。 isAlive(): 返回线程是否活动的。 getName(): 返回线程名。 setName(): 设置线程名。

可以通过直接从 threading.Thread 继承创建一个新的子类,并实例化后调用 start() 方法启动新线程,即它调用了线程的 run() 方法:

#!/usr/bin/python3

import threading
import time

exitFlag = 0

class myThread (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print ("开始线程:" + self.name)
        print_time(self.name, self.counter, 5)
        print ("退出线程:" + self.name)

def print_time(threadName, delay, counter):
    while counter:
        if exitFlag:
            threadName.exit()
        time.sleep(delay)
        print ("%s: %s" % (threadName, time.ctime(time.time())))
        counter -= 1

# 创建新线程
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

# 开启新线程
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print ("退出主线程")

'''
执行结果如下:
开始线程:Thread-1
开始线程:Thread-2
Thread-1: Wed Apr  6 11:46:46 2016
Thread-1: Wed Apr  6 11:46:47 2016
Thread-2: Wed Apr  6 11:46:47 2016
Thread-1: Wed Apr  6 11:46:48 2016
Thread-1: Wed Apr  6 11:46:49 2016
Thread-2: Wed Apr  6 11:46:49 2016
Thread-1: Wed Apr  6 11:46:50 2016
退出线程:Thread-1
Thread-2: Wed Apr  6 11:46:51 2016
Thread-2: Wed Apr  6 11:46:53 2016
Thread-2: Wed Apr  6 11:46:55 2016
退出线程:Thread-2
退出主线程
'''

线程同步

一涉及多线程,肯定跑不开多线程同步。 如果多个线程共同对某个数据修改,则可能出现不可预料的结果,为了保证数据的正确性,需要对多个线程进行同步。

使用 Thread 对象的 Lock 和 Rlock 可以实现简单的线程同步,这两个对象都有 acquire 方法和 release 方法,对于那些需要每次只允许一个线程操作的数据,可以将其操作放到 acquire 和 release 方法之间。

Lock(原始锁),锁定时不属于特定线程的同步基元件,最低级的同步基元件,支持with语句。

RLock(重入锁),acquire()/release()对可以嵌套,重入锁必须由获取它的线程释放,一旦线程获得了重入锁,同一个线程再次获取它将不会阻塞。但只有获取锁的线程最终release(嵌套的话,是最外层的release())才能释放锁,其他线程才可以加锁。

区别: Lock在锁定时不属于特定线程,也就是说,Lock可以在一个线程中上锁,在另一个线程中解锁。而对于RLock来说,只有当前线程才能释放本线程上的锁,即解铃还须系铃人

#!/usr/bin/python3

import threading
import time

class myThread (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print ("开启线程: " + self.name)
        # 获取锁,用于线程同步
        threadLock.acquire()
        print_time(self.name, self.counter, 3)
        # 释放锁,开启下一个线程
        threadLock.release()

def print_time(threadName, delay, counter):
    while counter:
        time.sleep(delay)
        print ("%s: %s" % (threadName, time.ctime(time.time())))
        counter -= 1

threadLock = threading.Lock()
threads = []

# 创建新线程
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

# 开启新线程
thread1.start()
thread2.start()

# 添加线程到线程列表
threads.append(thread1)
threads.append(thread2)

# 等待所有线程完成
for t in threads:
    t.join()
print ("退出主线程")

'''
执行结果如下:
开启线程: Thread-1
开启线程: Thread-2
Thread-1: Wed Apr  6 11:52:57 2016
Thread-1: Wed Apr  6 11:52:58 2016
Thread-1: Wed Apr  6 11:52:59 2016
Thread-2: Wed Apr  6 11:53:01 2016
Thread-2: Wed Apr  6 11:53:03 2016
Thread-2: Wed Apr  6 11:53:05 2016
退出主线程
'''

线程优先队列(Queue)

Python 的 Queue 模块中提供了同步的、线程安全的队列类,包括FIFO(先入先出)队列Queue,LIFO(后入先出)队列LifoQueue,和优先级队列 PriorityQueue。

这些队列都实现了锁原语,能够在多线程中直接使用,可以使用队列来实现线程间的同步。

Queue 模块中的常用方法: Queue.qsize()返回队列的大小 Queue.empty()如果队列为空,返回True,反之False Queue.full()如果队列满了,返回True,反之False Queue.full与maxsize大小对应 Queue.get([block[, timeout]])获取队列,timeout等待时间 Queue.get_nowait()相当Queue.get(False) Queue.put(item)写入队列,timeout等待时间 Queue.put_nowait(item)相当Queue.put(item, False) Queue.task_done()在完成一项工作之后,Queue.task_done()函数向任务已经完成的队列发送一个信号 Queue.join()实际上意味着等到队列为空,再执行别的操作

#!/usr/bin/python3

import queue
import threading
import time

exitFlag = 0

class myThread (threading.Thread):
    def __init__(self, threadID, name, q):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.q = q
    def run(self):
        print ("开启线程:" + self.name)
        process_data(self.name, self.q)
        print ("退出线程:" + self.name)

def process_data(threadName, q):
    while not exitFlag:
        queueLock.acquire()
        if not workQueue.empty():
            data = q.get()
            queueLock.release()
            print ("%s processing %s" % (threadName, data))
        else:
            queueLock.release()
        time.sleep(1)

threadList = ["Thread-1", "Thread-2", "Thread-3"]
nameList = ["One", "Two", "Three", "Four", "Five"]
queueLock = threading.Lock()
workQueue = queue.Queue(10)
threads = []
threadID = 1

# 创建新线程
for tName in threadList:
    thread = myThread(threadID, tName, workQueue)
    thread.start()
    threads.append(thread)
    threadID += 1

# 填充队列
queueLock.acquire()
for word in nameList:
    workQueue.put(word)
queueLock.release()

# 等待队列清空
while not workQueue.empty():
    pass

# 通知线程是时候退出
exitFlag = 1

# 等待所有线程完成
for t in threads:
    t.join()
print ("退出主线程")

'''
开启线程:Thread-1
开启线程:Thread-2
开启线程:Thread-3
Thread-3 processing One
Thread-1 processing Two
Thread-2 processing Three
Thread-3 processing Four
Thread-1 processing Five
退出线程:Thread-3
退出线程:Thread-2
退出线程:Thread-1
退出主线程
'''

参考资料

装饰器 Python闭包思想与用法浅析 Python3 多线程