python高级面试题

    科技2025-03-13  22

    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 = 5 def 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 = 5 def 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 = 5 def 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_decorator def 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 pickle cars = {"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 ABC class 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高级面试题

    Processed: 0.013, SQL: 8