MST

星途 面试题库

面试题:Python装饰器在元类中的应用

在Python中,元类用于创建类。请结合函数装饰器,实现一个元类,该元类能够自动为类中的所有实例方法添加一个装饰器,这个装饰器的功能是在方法执行前后打印特定的调试信息,如'Entering method [method_name]'和'Exiting method [method_name]'。
44.7万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
def debug_decorator(func):
    def wrapper(*args, **kwargs):
        print(f'Entering method {func.__name__}')
        result = func(*args, **kwargs)
        print(f'Exiting method {func.__name__}')
        return result
    return wrapper


def add_debug_to_methods(cls):
    for name, method in cls.__dict__.items():
        if callable(method) and not name.startswith('__'):
            setattr(cls, name, debug_decorator(method))
    return cls


class DebugMeta(type):
    def __new__(mcs, name, bases, namespace):
        new_cls = super().__new__(mcs, name, bases, namespace)
        return add_debug_to_methods(new_cls)


# 示例使用
class MyClass(metaclass=DebugMeta):
    def my_method(self):
        print('Inside my_method')


obj = MyClass()
obj.my_method()

上述代码实现步骤如下:

  1. 定义 debug_decorator 装饰器,用于在方法执行前后打印调试信息。
  2. 定义 add_debug_to_methods 函数,它遍历类的所有属性,对实例方法应用 debug_decorator 装饰器。
  3. 定义 DebugMeta 元类,在 __new__ 方法中创建类对象后,调用 add_debug_to_methods 函数为类的实例方法添加调试装饰器。
  4. 通过 MyClass 类展示如何使用这个元类,创建 MyClass 的实例并调用 my_method 方法时,会看到调试信息的打印。