python高级面试题_10个高级python面试问题
python高級面試題
With Python becoming more and more popular lately, many of you are probably undergoing technical interviews dealing with Python right now. In this post, I will list ten advanced Python interview questions and answers.
隨著Python最近越來越流行,你們中的許多人可能現在正在接受有關Python的技術面試。 在這篇文章中,我將列出十個高級Python訪談問題和答案。
These can be confusing and are directed at mid-level developers, who need an excellent understanding of Python as a language and how it works under the hood.
這些可能會令人困惑,并且針對的是中級開發人員,他們需要對Python作為一種語言及其幕后工作方式有很好的了解。
什么是Nolocal和Global關鍵字? (What Are Nolocal and Global Keywords Used For?)
These two keywords are used to change the scope of a previously declared variable. nolocal is often used when you need to access a variable in a nested function:
這兩個關鍵字用于更改先前聲明的變量的范圍。 當需要訪問嵌套函數中的變量時,通常使用nolocal :
def func1():x = 5
def func2():
nolocal x
print(x)
func2()
global is a more straightforward instruction. It makes a previously declared variable global. For example, consider this code:
global是更直接的說明。 它使先前聲明的變量成為全局變量。 例如,考慮以下代碼:
x = 5def func1():
print(x)
func1()
> 5
Since x is declared before the function call, func1 can access it. However, if you try to change it:
由于x是在函數調用之前聲明的,因此func1可以訪問它。 但是,如果您嘗試更改它:
x = 5def func2():
x += 3
func2()
> UnboundLocalError: local variable 'c' referenced before assignment
To make it work, we need to indicate that by x we mean the global variable x:
為了使它起作用,我們需要用x表示全局變量x :
x = 5def func2():
global x
x += 3
func2()
類方法和靜態方法有什么區別? (What Is the Difference Between Classmethod and Staticmethod?)
Both of them define a class method that can be called without instantiating an object of the class. The only difference is in their signature:
它們都定義了一個類方法,可以在不實例化該類的對象的情況下調用該方法。 唯一的區別在于它們的簽名:
class A:@staticmethod
def func1():
pass
@classmethod
def func2(cls):
pass
As you can see, the classmethod accepts an implicit argument cls, which will be set to the class A itself. One common use case for classmethod is creating alternative inheritable constructors.
如您所見, classmethod接受一個隱式參數cls ,它將被設置為類A本身。 一個常見的用例classmethod是創造其他遺傳構造。
什么是GIL?如何繞過GIL? (What Is GIL and What Are Some of the Ways to Get Around It?)
GIL stands for the Global Interpreter Lock and it is a mechanism Python uses for concurrency. It is built deep into the Python system and it is not possible at the moment to get rid of it. The major downside of GIL is that it makes threading not truly concurrent. It locks the interpreter, and even though it looks like you are working with threads, they are not executed at the same time, resulting in performance losses. Here are some ways of getting around it:
GIL代表全局解釋器鎖,它是Python用于并發的一種機制。 它內置在Python系統中,目前尚無法擺脫。 GIL的主要缺點是它使線程不是真正的并發。 它鎖定了解釋器,即使看起來好像您正在使用線程,它們也不會同時執行,從而導致性能損失。 以下是一些解決方法:
multiprocessing module. It lets you spawn new Python processes and manage them the same way you would manage threads.
multiprocessing模塊。 它使您可以生成新的Python進程并以與管理線程相同的方式對其進行管理。
asyncio module. It effectively enables asynchronous programming and adds the async/await syntax. While it does not solve the GIL problem, it will make the code way more readable and clearer.
asyncio模塊。 它有效地啟用了異步編程,并添加了async/await語法。 雖然它不能解決GIL問題,但可以使代碼更易讀和清楚。
Stackless Python. This is a fork of Python without GIL. It’s most notable use is as a backend for the EVE Online game.
無堆棧Python 。 這是沒有GIL的Python的分支。 它最顯著的用途是作為EVE Online游戲的后端。
什么是元類以及何時使用它們? (What Are Metaclasses and When Are They Used?)
Metaclasses are classes for classes. A metaclass can specify certain behaviour that is common for many classes for cases when inheritance will be too messy. One common metaclass is ABCMeta, which is used to create abstract classes.
元類是類的類。 對于繼承過于混亂的情況,元類可以指定許多類通用的某些行為。 一種常見的元類是ABCMeta ,用于創建抽象類。
Metaclasses and metaprogramming in Python is a huge topic. Be sure to read more about it if you are interested in it.
Python中的元類和元編程是一個巨大的話題。 如果您對此感興趣,請務必有關它的內容。
什么是類型注釋? 什么是通用類型注釋? (What Are Type Annotations? What Are Generic Type Annotations?)
While Python is a dynamically typed language, there is a way to annotate types for clarity purposes. These are the built-in types:
雖然Python是一種動態類型化的語言,但是為了清晰起見,有一種方法可以對類型進行注釋。 這些是內置類型:
int
int
float
float
bool
bool
str
str
bytes
bytes
Complex types are available from the typing module:
復雜類型可從typing模塊中獲得:
List
List
Set
Set
Dict
Dict
Tuple
Tuple
Optional
Optional
- etc. 等等
Here is how you would define a function with type annotations:
這是定義帶類型注釋的函數的方式:
def func1(x: int, y: str) -> bool:return False
Generic type annotations are annotations that take another type as a parameter, allowing you to specify complex logic:
泛型類型注釋是采用另一種類型作為參數的注釋,允許您指定復雜的邏輯:
List[int]
List[int]
Optional[List[int]]
Optional[List[int]]
Tuple[bool]
Tuple[bool]
- etc. 等等
Note that these are only used for warnings and static type checking. You will not be guaranteed these types at runtime.
請注意,這些僅用于警告和靜態類型檢查。 您將無法在運行時保證這些類型。
什么是發電機功能? 編寫自己的Range版本 (What Are Generator Functions? Write Your Own Version of Range)
Generator functions are functions that can suspend their execution after returning a value, in order to resume it at some later time and return another value. This is made possible by the yield keyword, which you use in place of return. The most common generator function you have worked with is the range. Here is one way of implementing it (only works with positive step, I will leave it as an exercise to make one that supports negative steps):
生成器函數是可以在返回值后暫停執行的函數,以便稍后再恢復它并返回另一個值。 這可以通過yield關鍵字來實現,您可以使用它來代替return。 您使用過的最常見的生成器功能是range 。 這是實現它的一種方法(僅適用于積極的步驟,我將其作為一種練習來支持消極的步驟):
def range(start, end, step):cur = start
while cur > end:
yield cur
cur += step
什么是Python中的裝飾器? (What Are Decorators in Python?)
Decorators in Python are used to modify behaviours of functions. For example, if you want to log all calls to a particular set of functions, cache its parameters and return values, perform benchmarks, etc.
Python中的裝飾器用于修改函數的行為。 例如,如果要記錄對一組特定函數的所有調用,緩存其參數和返回值,執行基準測試等。
Decorators are prefixed with the @ symbol and placed right before function declaration:
裝飾器以@符號為前綴,并放在函數聲明之前:
@my_decoratordef func1():
pass
什么是Python中的酸洗和酸洗? (What Is Pickling and Unpickling in Python?)
Pickling is just the Python way of saying serializing. Pickling lets you serialize an object into a string (or anything else you choose) in order to be persisted on storage or sent over the network. Unpickling is the process of restoring the original object from a pickled string. Pickling is not secure. Only unpickle objects from trusted sources.
酸洗只是Python所說的序列化方式。 借助酸洗,您可以將對象序列化為字符串(或其他任何選擇),以便持久存儲在網絡上或通過網絡發送。 取消腌制是從腌制的字符串中還原原始對象的過程。 酸洗不安全。 僅釋放受信任來源的對象。
Here is how you would pickle a basic data structure:
這是腌制基本數據結構的方法:
import picklecars = {"Subaru": "best car", "Toyota": "no i am the best car"} cars_serialized = pickle.dumps(cars)
# cars_serialized is a byte string new_cars = pickle.loads(cars_serialized)
Python函數中的*args和**kwargs是什么? (What are *args and **kwargs in Python functions?)
These deal closely with unpacking. If you put *args in a function's parameter list, all unnamed arguments will be stored in the args array. **kwargs works the same way, but for named parameters:
這些與拆箱密切相關。 如果將*args放在函數的參數列表中,則所有未命名的參數將存儲在args數組中。 **kwargs工作方式相同,但對于命名參數:
def func1(*args, **kwargs):print(args)
print(kwargs)
func1(1, 'abc', lol='lmao')
> [1, 'abc']
> {"lol": "lmao"}
什么是.pyc文件? (What Are .pyc Files Used For?)
.pyc files contain Python bytecode, the same way as .class files in Java. Python is still considered an interpreted language, though, since this compilation phase occurs when you run the program, while in Java these a clearly separated.
.pyc文件包含Python字節碼,與Java中的.class文件相同。 但是,Python仍被認為是一種解釋語言,因為在運行程序時會發生此編譯階段,而在Java中,這是明顯分開的。
您如何在Python中定義抽象類? (How do you define abstract classes in Python?)
You define an abstract class by inheriting the ABC class from the abc module:
您可以通過從abc模塊繼承ABC類來定義抽象類:
from abc import ABCclass AbstractCar(ABC):
@abstractmethod
def drive(self):
pass
To implement the class, just inherit it:
要實現該類,只需繼承它:
class ToyotaSupra(AbstractCar):def drive(self):
print('brrrr sutututu')
結束語 (Closing Notes)
Thank you for reading and I wish you all the best in your next interview.
感謝您的閱讀,并祝您在下次面試中一切順利。
資源資源 (Resources)
Python Context Managers in Depth
深入的Python上下文管理器
翻譯自: https://medium.com/better-programming/10-advanced-python-interview-questions-d36e3429601b
python高級面試題
總結
以上是生活随笔為你收集整理的python高级面试题_10个高级python面试问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 店盈通:拼多多自然搜索关键词排名原理解析
- 下一篇: python爬取vip小说章节_怎么用p