interview
python-handwritten-code
按照题目要求写出对应的 Python 装饰器

Python 手写代码面试题, 按照题目要求写出对应的 Python 装饰器

Python 手写代码面试题, 按照题目要求写出对应的 Python 装饰器

QA

Step 1

Q:: 什么是Python装饰器?

A:: Python装饰器是修改其他函数功能的函数。装饰器可以让我们在不修改已有函数代码的前提下,增加额外的功能。它们通常用于有横切关注点的功能,比如日志记录、性能计数器、事务处理等。

Step 2

Q:: 如何创建一个简单的Python装饰器?

A:: 一个简单的Python装饰器如下所示:

 
def my_decorator(func):
    def wrapper(*args, **kwargs):
        print('Something is happening before the function is called.')
        result = func(*args, **kwargs)
        print('Something is happening after the function is called.')
        return result
    return wrapper
 
@my_decorator
def say_hello():
    print('Hello!')
 
say_hello()
 

这个例子中,my_decorator 是一个装饰器,它在 say_hello 函数前后打印一些信息。

Step 3

Q:: 装饰器如何处理带参数的函数?

A:: 装饰器可以使用 *args**kwargs 来处理带参数的函数。例如:

 
def my_decorator(func):
    def wrapper(*args, **kwargs):
        print('Arguments were:', args, kwargs)
        return func(*args, **kwargs)
    return wrapper
 
@my_decorator
def display_info(name, age):
    print(f'Display info: {name}, {age}')
 
display_info('John', 25)
 

这个装饰器在调用函数前打印函数的参数。

Step 4

Q:: 如何编写一个带参数的装饰器?

A:: 带参数的装饰器需要多一层嵌套。例如:

 
def decorator_with_args(decorator_arg1, decorator_arg2):
    def decorator(func):
        def wrapper(*args, **kwargs):
            print(f'Decorator arguments: {decorator_arg1}, {decorator_arg2}')
            return func(*args, **kwargs)
        return wrapper
    return decorator
 
@decorator_with_args('arg1', 'arg2')
def say_hello():
    print('Hello!')
 
say_hello()
 

这个装饰器在执行时会打印装饰器的参数。

Step 5

Q:: 如何使用类来实现装饰器?

A:: 可以使用类的 __call__ 方法来实现装饰器。例如:

 
class MyDecorator:
    def __init__(self, func):
        self.func = func
 
    def __call__(self, *args, **kwargs):
        print('Something is happening before the function is called.')
        result = self.func(*args, **kwargs)
        print('Something is happening after the function is called.')
        return result
 
@MyDecorator
def say_hello():
    print('Hello!')
 
say_hello()
 

这个例子中,MyDecorator 类实现了一个装饰器。

用途

面试这些内容是为了评估候选人对Python高级特性及其应用的掌握程度。装饰器在实际生产环境中被广泛用于跨切面关注点(如日志、性能监控、权限验证等)的功能实现,确保代码的可重用性和模块化。此外,装饰器在框架设计和库开发中也是常用的工具,例如Flask的路由装饰器,Django的权限装饰器等。\n

相关问题

🦆
Python中的闭包是什么?

闭包是一个函数对象,即使在其词法作用域外被执行,该函数也能访问其词法作用域内的变量。例如:

 
def outer_func(x):
    def inner_func(y):
        return x + y
    return inner_func
 
closure = outer_func(10)
print(closure(5))  # 输出15
 
🦆
请解释一下Python的函数式编程?

函数式编程是一种编程范式,强调使用函数和不可变数据。Python支持函数式编程特性,如高阶函数、匿名函数(lambda)、map、filter和reduce。例如:

 
squares = list(map(lambda x: x**2, range(10)))
print(squares)  # 输出:[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
 
🦆
Python的生成器和迭代器是什么?

生成器是用来创建迭代器的一种简单而强大的工具。生成器使用 yield 关键字,每次 yield 语句被执行时,生成器的状态会被冻结。迭代器是实现了 __iter____next__ 方法的对象,可以用来遍历容器中的数据。例如:

 
def simple_generator():
    yield 1
    yield 2
    yield 3
 
gen = simple_generator()
for value in gen:
    print(value)  # 输出1, 2, 3