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: